SemaStmt.cpp 145 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953
  1. //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
  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 semantic analysis for statements.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTDiagnostic.h"
  16. #include "clang/AST/CharUnits.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/EvaluatedExprVisitor.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/ExprObjC.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/AST/TypeOrdering.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/Lex/Preprocessor.h"
  29. #include "clang/Sema/Initialization.h"
  30. #include "clang/Sema/Lookup.h"
  31. #include "clang/Sema/Scope.h"
  32. #include "clang/Sema/ScopeInfo.h"
  33. #include "llvm/ADT/ArrayRef.h"
  34. #include "llvm/ADT/DenseMap.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/ADT/SmallPtrSet.h"
  37. #include "llvm/ADT/SmallString.h"
  38. #include "llvm/ADT/SmallVector.h"
  39. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  40. using namespace clang;
  41. using namespace sema;
  42. StmtResult Sema::ActOnExprStmt(ExprResult FE) {
  43. if (FE.isInvalid())
  44. return StmtError();
  45. FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
  46. /*DiscardedValue*/ true);
  47. if (FE.isInvalid())
  48. return StmtError();
  49. // C99 6.8.3p2: The expression in an expression statement is evaluated as a
  50. // void expression for its side effects. Conversion to void allows any
  51. // operand, even incomplete types.
  52. // Same thing in for stmt first clause (when expr) and third clause.
  53. return StmtResult(FE.getAs<Stmt>());
  54. }
  55. StmtResult Sema::ActOnExprStmtError() {
  56. DiscardCleanupsInEvaluationContext();
  57. return StmtError();
  58. }
  59. StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
  60. bool HasLeadingEmptyMacro) {
  61. return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
  62. }
  63. StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
  64. SourceLocation EndLoc) {
  65. DeclGroupRef DG = dg.get();
  66. // If we have an invalid decl, just return an error.
  67. if (DG.isNull()) return StmtError();
  68. return new (Context) DeclStmt(DG, StartLoc, EndLoc);
  69. }
  70. void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
  71. DeclGroupRef DG = dg.get();
  72. // If we don't have a declaration, or we have an invalid declaration,
  73. // just return.
  74. if (DG.isNull() || !DG.isSingleDecl())
  75. return;
  76. Decl *decl = DG.getSingleDecl();
  77. if (!decl || decl->isInvalidDecl())
  78. return;
  79. // Only variable declarations are permitted.
  80. VarDecl *var = dyn_cast<VarDecl>(decl);
  81. if (!var) {
  82. Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
  83. decl->setInvalidDecl();
  84. return;
  85. }
  86. // foreach variables are never actually initialized in the way that
  87. // the parser came up with.
  88. var->setInit(nullptr);
  89. // In ARC, we don't need to retain the iteration variable of a fast
  90. // enumeration loop. Rather than actually trying to catch that
  91. // during declaration processing, we remove the consequences here.
  92. if (getLangOpts().ObjCAutoRefCount) {
  93. QualType type = var->getType();
  94. // Only do this if we inferred the lifetime. Inferred lifetime
  95. // will show up as a local qualifier because explicit lifetime
  96. // should have shown up as an AttributedType instead.
  97. if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
  98. // Add 'const' and mark the variable as pseudo-strong.
  99. var->setType(type.withConst());
  100. var->setARCPseudoStrong(true);
  101. }
  102. }
  103. }
  104. /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
  105. /// For '==' and '!=', suggest fixits for '=' or '|='.
  106. ///
  107. /// Adding a cast to void (or other expression wrappers) will prevent the
  108. /// warning from firing.
  109. static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
  110. SourceLocation Loc;
  111. bool IsNotEqual, CanAssign, IsRelational;
  112. if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  113. if (!Op->isComparisonOp())
  114. return false;
  115. IsRelational = Op->isRelationalOp();
  116. Loc = Op->getOperatorLoc();
  117. IsNotEqual = Op->getOpcode() == BO_NE;
  118. CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
  119. } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  120. switch (Op->getOperator()) {
  121. default:
  122. return false;
  123. case OO_EqualEqual:
  124. case OO_ExclaimEqual:
  125. IsRelational = false;
  126. break;
  127. case OO_Less:
  128. case OO_Greater:
  129. case OO_GreaterEqual:
  130. case OO_LessEqual:
  131. IsRelational = true;
  132. break;
  133. }
  134. Loc = Op->getOperatorLoc();
  135. IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
  136. CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
  137. } else {
  138. // Not a typo-prone comparison.
  139. return false;
  140. }
  141. // Suppress warnings when the operator, suspicious as it may be, comes from
  142. // a macro expansion.
  143. if (S.SourceMgr.isMacroBodyExpansion(Loc))
  144. return false;
  145. S.Diag(Loc, diag::warn_unused_comparison)
  146. << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
  147. // If the LHS is a plausible entity to assign to, provide a fixit hint to
  148. // correct common typos.
  149. if (!IsRelational && CanAssign) {
  150. if (IsNotEqual)
  151. S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
  152. << FixItHint::CreateReplacement(Loc, "|=");
  153. else
  154. S.Diag(Loc, diag::note_equality_comparison_to_assign)
  155. << FixItHint::CreateReplacement(Loc, "=");
  156. }
  157. return true;
  158. }
  159. void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
  160. if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
  161. return DiagnoseUnusedExprResult(Label->getSubStmt());
  162. const Expr *E = dyn_cast_or_null<Expr>(S);
  163. if (!E)
  164. return;
  165. // If we are in an unevaluated expression context, then there can be no unused
  166. // results because the results aren't expected to be used in the first place.
  167. if (isUnevaluatedContext())
  168. return;
  169. SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
  170. // In most cases, we don't want to warn if the expression is written in a
  171. // macro body, or if the macro comes from a system header. If the offending
  172. // expression is a call to a function with the warn_unused_result attribute,
  173. // we warn no matter the location. Because of the order in which the various
  174. // checks need to happen, we factor out the macro-related test here.
  175. bool ShouldSuppress =
  176. SourceMgr.isMacroBodyExpansion(ExprLoc) ||
  177. SourceMgr.isInSystemMacro(ExprLoc);
  178. const Expr *WarnExpr;
  179. SourceLocation Loc;
  180. SourceRange R1, R2;
  181. if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
  182. return;
  183. // If this is a GNU statement expression expanded from a macro, it is probably
  184. // unused because it is a function-like macro that can be used as either an
  185. // expression or statement. Don't warn, because it is almost certainly a
  186. // false positive.
  187. if (isa<StmtExpr>(E) && Loc.isMacroID())
  188. return;
  189. // Okay, we have an unused result. Depending on what the base expression is,
  190. // we might want to make a more specific diagnostic. Check for one of these
  191. // cases now.
  192. unsigned DiagID = diag::warn_unused_expr;
  193. if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
  194. E = Temps->getSubExpr();
  195. if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
  196. E = TempExpr->getSubExpr();
  197. if (DiagnoseUnusedComparison(*this, E))
  198. return;
  199. E = WarnExpr;
  200. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  201. if (E->getType()->isVoidType())
  202. return;
  203. // If the callee has attribute pure, const, or warn_unused_result, warn with
  204. // a more specific message to make it clear what is happening. If the call
  205. // is written in a macro body, only warn if it has the warn_unused_result
  206. // attribute.
  207. if (const Decl *FD = CE->getCalleeDecl()) {
  208. const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
  209. if (Func ? Func->hasUnusedResultAttr()
  210. : FD->hasAttr<WarnUnusedResultAttr>()) {
  211. Diag(Loc, diag::warn_unused_result) << R1 << R2;
  212. return;
  213. }
  214. if (ShouldSuppress)
  215. return;
  216. if (FD->hasAttr<PureAttr>()) {
  217. Diag(Loc, diag::warn_hlsl_unused_call) << R1 << R2 << "pure"; // HLSL Change: rather than warn_unused_call
  218. return;
  219. }
  220. if (FD->hasAttr<ConstAttr>()) {
  221. Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
  222. return;
  223. }
  224. }
  225. } else if (ShouldSuppress)
  226. return;
  227. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
  228. if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
  229. Diag(Loc, diag::err_arc_unused_init_message) << R1;
  230. return;
  231. }
  232. const ObjCMethodDecl *MD = ME->getMethodDecl();
  233. if (MD) {
  234. if (MD->hasAttr<WarnUnusedResultAttr>()) {
  235. Diag(Loc, diag::warn_unused_result) << R1 << R2;
  236. return;
  237. }
  238. }
  239. } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  240. const Expr *Source = POE->getSyntacticForm();
  241. if (isa<ObjCSubscriptRefExpr>(Source))
  242. DiagID = diag::warn_unused_container_subscript_expr;
  243. else
  244. DiagID = diag::warn_unused_property_expr;
  245. } else if (const CXXFunctionalCastExpr *FC
  246. = dyn_cast<CXXFunctionalCastExpr>(E)) {
  247. if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
  248. isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
  249. return;
  250. }
  251. // Diagnose "(void*) blah" as a typo for "(void) blah".
  252. else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
  253. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  254. QualType T = TI->getType();
  255. // We really do want to use the non-canonical type here.
  256. if (T == Context.VoidPtrTy) {
  257. PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
  258. Diag(Loc, diag::warn_unused_voidptr)
  259. << FixItHint::CreateRemoval(TL.getStarLoc());
  260. return;
  261. }
  262. }
  263. if (E->isGLValue() && E->getType().isVolatileQualified()) {
  264. Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
  265. return;
  266. }
  267. DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
  268. }
  269. void Sema::ActOnStartOfCompoundStmt() {
  270. PushCompoundScope();
  271. }
  272. void Sema::ActOnFinishOfCompoundStmt() {
  273. PopCompoundScope();
  274. }
  275. sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
  276. return getCurFunction()->CompoundScopes.back();
  277. }
  278. StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
  279. ArrayRef<Stmt *> Elts, bool isStmtExpr) {
  280. const unsigned NumElts = Elts.size();
  281. // If we're in C89 mode, check that we don't have any decls after stmts. If
  282. // so, emit an extension diagnostic.
  283. if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
  284. // Note that __extension__ can be around a decl.
  285. unsigned i = 0;
  286. // Skip over all declarations.
  287. for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
  288. /*empty*/;
  289. // We found the end of the list or a statement. Scan for another declstmt.
  290. for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
  291. /*empty*/;
  292. if (i != NumElts) {
  293. Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
  294. Diag(D->getLocation(), diag::ext_mixed_decls_code);
  295. }
  296. }
  297. // Warn about unused expressions in statements.
  298. for (unsigned i = 0; i != NumElts; ++i) {
  299. // Ignore statements that are last in a statement expression.
  300. if (isStmtExpr && i == NumElts - 1)
  301. continue;
  302. DiagnoseUnusedExprResult(Elts[i]);
  303. }
  304. // Check for suspicious empty body (null statement) in `for' and `while'
  305. // statements. Don't do anything for template instantiations, this just adds
  306. // noise.
  307. if (NumElts != 0 && !CurrentInstantiationScope &&
  308. getCurCompoundScope().HasEmptyLoopBodies) {
  309. for (unsigned i = 0; i != NumElts - 1; ++i)
  310. DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
  311. }
  312. return new (Context) CompoundStmt(Context, Elts, L, R);
  313. }
  314. StmtResult
  315. Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
  316. SourceLocation DotDotDotLoc, Expr *RHSVal,
  317. SourceLocation ColonLoc) {
  318. assert(LHSVal && "missing expression in case statement");
  319. if (getCurFunction()->SwitchStack.empty()) {
  320. Diag(CaseLoc, diag::err_case_not_in_switch);
  321. return StmtError();
  322. }
  323. ExprResult LHS =
  324. CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
  325. if (!getLangOpts().CPlusPlus11)
  326. return VerifyIntegerConstantExpression(E);
  327. if (Expr *CondExpr =
  328. getCurFunction()->SwitchStack.back()->getCond()) {
  329. QualType CondType = CondExpr->getType();
  330. llvm::APSInt TempVal;
  331. return CheckConvertedConstantExpression(E, CondType, TempVal,
  332. CCEK_CaseValue);
  333. }
  334. return ExprError();
  335. });
  336. if (LHS.isInvalid())
  337. return StmtError();
  338. LHSVal = LHS.get();
  339. if (!getLangOpts().CPlusPlus11 && getLangOpts().HLSLVersion < 2017) {
  340. // C99 6.8.4.2p3: The expression shall be an integer constant.
  341. // However, GCC allows any evaluatable integer expression.
  342. if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
  343. LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
  344. if (!LHSVal)
  345. return StmtError();
  346. }
  347. // GCC extension: The expression shall be an integer constant.
  348. if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
  349. RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
  350. // Recover from an error by just forgetting about it.
  351. }
  352. }
  353. LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
  354. getLangOpts().CPlusPlus11);
  355. if (LHS.isInvalid())
  356. return StmtError();
  357. auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
  358. getLangOpts().CPlusPlus11)
  359. : ExprResult();
  360. if (RHS.isInvalid())
  361. return StmtError();
  362. CaseStmt *CS = new (Context)
  363. CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
  364. getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
  365. return CS;
  366. }
  367. /// ActOnCaseStmtBody - This installs a statement as the body of a case.
  368. void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
  369. DiagnoseUnusedExprResult(SubStmt);
  370. CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
  371. CS->setSubStmt(SubStmt);
  372. }
  373. StmtResult
  374. Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
  375. Stmt *SubStmt, Scope *CurScope) {
  376. DiagnoseUnusedExprResult(SubStmt);
  377. if (getCurFunction()->SwitchStack.empty()) {
  378. Diag(DefaultLoc, diag::err_default_not_in_switch);
  379. return SubStmt;
  380. }
  381. DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
  382. getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
  383. return DS;
  384. }
  385. StmtResult
  386. Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
  387. SourceLocation ColonLoc, Stmt *SubStmt) {
  388. // If the label was multiply defined, reject it now.
  389. if (TheDecl->getStmt()) {
  390. Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
  391. Diag(TheDecl->getLocation(), diag::note_previous_definition);
  392. return SubStmt;
  393. }
  394. // Otherwise, things are good. Fill in the declaration and return it.
  395. LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
  396. TheDecl->setStmt(LS);
  397. if (!TheDecl->isGnuLocal()) {
  398. TheDecl->setLocStart(IdentLoc);
  399. if (!TheDecl->isMSAsmLabel()) {
  400. // Don't update the location of MS ASM labels. These will result in
  401. // a diagnostic, and changing the location here will mess that up.
  402. TheDecl->setLocation(IdentLoc);
  403. }
  404. }
  405. return LS;
  406. }
  407. StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
  408. ArrayRef<const Attr*> Attrs,
  409. Stmt *SubStmt) {
  410. // HLSL Change - Validate inconsistent attributes being set on statemetns.
  411. if (getLangOpts().HLSL) {
  412. bool loopFound = false;
  413. bool unrollFound = false;
  414. bool fastOptFound = false;
  415. for (const Attr* a : Attrs) {
  416. unrollFound = unrollFound || (a->getKind() == attr::HLSLUnroll);
  417. fastOptFound = fastOptFound || (a->getKind() == attr::HLSLFastOpt);
  418. loopFound = loopFound || (a->getKind() == attr::HLSLLoop);
  419. }
  420. if (loopFound && unrollFound) {
  421. Diag(AttrLoc, diag::err_attributes_are_not_compatible) << "loop" << "unroll";
  422. }
  423. if (fastOptFound && unrollFound) {
  424. Diag(AttrLoc, diag::err_attributes_are_not_compatible) << "fastopt" << "unroll";
  425. }
  426. }
  427. // HLSL Change Ends
  428. // Fill in the declaration and return it.
  429. AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
  430. return LS;
  431. }
  432. StmtResult
  433. Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
  434. Stmt *thenStmt, SourceLocation ElseLoc,
  435. Stmt *elseStmt) {
  436. // If the condition was invalid, discard the if statement. We could recover
  437. // better by replacing it with a valid expr, but don't do that yet.
  438. if (!CondVal.get() && !CondVar) {
  439. getCurFunction()->setHasDroppedStmt();
  440. return StmtError();
  441. }
  442. ExprResult CondResult(CondVal.release());
  443. VarDecl *ConditionVar = nullptr;
  444. if (CondVar) {
  445. ConditionVar = cast<VarDecl>(CondVar);
  446. CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
  447. CondResult = ActOnFinishFullExpr(CondResult.get(), IfLoc);
  448. if (CondResult.isInvalid())
  449. return StmtError();
  450. }
  451. Expr *ConditionExpr = CondResult.getAs<Expr>();
  452. if (!ConditionExpr)
  453. return StmtError();
  454. // HLSL Change Begin.
  455. hlsl::DiagnoseControlFlowConditionForHLSL(this, ConditionExpr, "if");
  456. // HLSL Change End.
  457. DiagnoseUnusedExprResult(thenStmt);
  458. if (!elseStmt) {
  459. DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
  460. diag::warn_empty_if_body);
  461. }
  462. DiagnoseUnusedExprResult(elseStmt);
  463. return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
  464. thenStmt, ElseLoc, elseStmt);
  465. }
  466. namespace {
  467. struct CaseCompareFunctor {
  468. bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
  469. const llvm::APSInt &RHS) {
  470. return LHS.first < RHS;
  471. }
  472. bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
  473. const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
  474. return LHS.first < RHS.first;
  475. }
  476. bool operator()(const llvm::APSInt &LHS,
  477. const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
  478. return LHS < RHS.first;
  479. }
  480. };
  481. }
  482. /// CmpCaseVals - Comparison predicate for sorting case values.
  483. ///
  484. static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
  485. const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
  486. if (lhs.first < rhs.first)
  487. return true;
  488. if (lhs.first == rhs.first &&
  489. lhs.second->getCaseLoc().getRawEncoding()
  490. < rhs.second->getCaseLoc().getRawEncoding())
  491. return true;
  492. return false;
  493. }
  494. /// CmpEnumVals - Comparison predicate for sorting enumeration values.
  495. ///
  496. static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
  497. const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
  498. {
  499. return lhs.first < rhs.first;
  500. }
  501. /// EqEnumVals - Comparison preficate for uniqing enumeration values.
  502. ///
  503. static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
  504. const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
  505. {
  506. return lhs.first == rhs.first;
  507. }
  508. /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
  509. /// potentially integral-promoted expression @p expr.
  510. static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
  511. if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
  512. expr = cleanups->getSubExpr();
  513. while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
  514. if (impcast->getCastKind() != CK_IntegralCast) break;
  515. expr = impcast->getSubExpr();
  516. }
  517. return expr->getType();
  518. }
  519. StmtResult
  520. Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
  521. Decl *CondVar) {
  522. ExprResult CondResult;
  523. VarDecl *ConditionVar = nullptr;
  524. if (CondVar) {
  525. ConditionVar = cast<VarDecl>(CondVar);
  526. CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
  527. if (CondResult.isInvalid())
  528. return StmtError();
  529. Cond = CondResult.get();
  530. }
  531. if (!Cond)
  532. return StmtError();
  533. // HLSL Change Begins.
  534. if (Cond->getType()->isFloatingType()) {
  535. // Cast float to int for switch.
  536. QualType intTy = Context.getIntTypeForBitwidth(32, /*isSigned*/true);
  537. ExprResult Res = ImplicitCastExpr::Create(Context, intTy, CK_FloatingToIntegral, Cond,
  538. nullptr, Cond->getValueKind());
  539. Cond = Res.get();
  540. }
  541. // HLSL Change Ends.
  542. class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
  543. Expr *Cond;
  544. public:
  545. SwitchConvertDiagnoser(Expr *Cond)
  546. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
  547. Cond(Cond) {}
  548. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  549. QualType T) override {
  550. return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
  551. }
  552. SemaDiagnosticBuilder diagnoseIncomplete(
  553. Sema &S, SourceLocation Loc, QualType T) override {
  554. return S.Diag(Loc, diag::err_switch_incomplete_class_type)
  555. << T << Cond->getSourceRange();
  556. }
  557. SemaDiagnosticBuilder diagnoseExplicitConv(
  558. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  559. return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
  560. }
  561. SemaDiagnosticBuilder noteExplicitConv(
  562. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  563. return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
  564. << ConvTy->isEnumeralType() << ConvTy;
  565. }
  566. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  567. QualType T) override {
  568. return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
  569. }
  570. SemaDiagnosticBuilder noteAmbiguous(
  571. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  572. return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
  573. << ConvTy->isEnumeralType() << ConvTy;
  574. }
  575. SemaDiagnosticBuilder diagnoseConversion(
  576. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  577. llvm_unreachable("conversion functions are permitted");
  578. }
  579. } SwitchDiagnoser(Cond);
  580. CondResult =
  581. PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
  582. if (CondResult.isInvalid()) return StmtError();
  583. Cond = CondResult.get();
  584. // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
  585. CondResult = UsualUnaryConversions(Cond);
  586. if (CondResult.isInvalid()) return StmtError();
  587. Cond = CondResult.get();
  588. CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
  589. if (CondResult.isInvalid())
  590. return StmtError();
  591. Cond = CondResult.get();
  592. getCurFunction()->setHasBranchIntoScope();
  593. SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
  594. getCurFunction()->SwitchStack.push_back(SS);
  595. return SS;
  596. }
  597. static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
  598. Val = Val.extOrTrunc(BitWidth);
  599. Val.setIsSigned(IsSigned);
  600. }
  601. /// Check the specified case value is in range for the given unpromoted switch
  602. /// type.
  603. static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
  604. unsigned UnpromotedWidth, bool UnpromotedSign) {
  605. // If the case value was signed and negative and the switch expression is
  606. // unsigned, don't bother to warn: this is implementation-defined behavior.
  607. // FIXME: Introduce a second, default-ignored warning for this case?
  608. if (UnpromotedWidth < Val.getBitWidth()) {
  609. llvm::APSInt ConvVal(Val);
  610. AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
  611. AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
  612. // FIXME: Use different diagnostics for overflow in conversion to promoted
  613. // type versus "switch expression cannot have this value". Use proper
  614. // IntRange checking rather than just looking at the unpromoted type here.
  615. if (ConvVal != Val)
  616. S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
  617. << ConvVal.toString(10);
  618. }
  619. }
  620. typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
  621. /// Returns true if we should emit a diagnostic about this case expression not
  622. /// being a part of the enum used in the switch controlling expression.
  623. static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
  624. const EnumDecl *ED,
  625. const Expr *CaseExpr,
  626. EnumValsTy::iterator &EI,
  627. EnumValsTy::iterator &EIEnd,
  628. const llvm::APSInt &Val) {
  629. bool FlagType = ED->hasAttr<FlagEnumAttr>();
  630. if (const DeclRefExpr *DRE =
  631. dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
  632. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  633. QualType VarType = VD->getType();
  634. QualType EnumType = S.Context.getTypeDeclType(ED);
  635. if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
  636. S.Context.hasSameUnqualifiedType(EnumType, VarType))
  637. return false;
  638. }
  639. }
  640. if (FlagType) {
  641. return !S.IsValueInFlagEnum(ED, Val, false);
  642. } else {
  643. while (EI != EIEnd && EI->first < Val)
  644. EI++;
  645. if (EI != EIEnd && EI->first == Val)
  646. return false;
  647. }
  648. return true;
  649. }
  650. StmtResult
  651. Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
  652. Stmt *BodyStmt) {
  653. SwitchStmt *SS = cast<SwitchStmt>(Switch);
  654. assert(SS == getCurFunction()->SwitchStack.back() &&
  655. "switch stack missing push/pop!");
  656. getCurFunction()->SwitchStack.pop_back();
  657. if (!BodyStmt) return StmtError();
  658. SS->setBody(BodyStmt, SwitchLoc);
  659. Expr *CondExpr = SS->getCond();
  660. if (!CondExpr) return StmtError();
  661. QualType CondType = CondExpr->getType();
  662. Expr *CondExprBeforePromotion = CondExpr;
  663. QualType CondTypeBeforePromotion =
  664. GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
  665. // C++ 6.4.2.p2:
  666. // Integral promotions are performed (on the switch condition).
  667. //
  668. // A case value unrepresentable by the original switch condition
  669. // type (before the promotion) doesn't make sense, even when it can
  670. // be represented by the promoted type. Therefore we need to find
  671. // the pre-promotion type of the switch condition.
  672. if (!CondExpr->isTypeDependent()) {
  673. // We have already converted the expression to an integral or enumeration
  674. // type, when we started the switch statement. If we don't have an
  675. // appropriate type now, just return an error.
  676. if (!CondType->isIntegralOrEnumerationType())
  677. return StmtError();
  678. if (CondExpr->isKnownToHaveBooleanValue()) {
  679. // switch(bool_expr) {...} is often a programmer error, e.g.
  680. // switch(n && mask) { ... } // Doh - should be "n & mask".
  681. // One can always use an if statement instead of switch(bool_expr).
  682. Diag(SwitchLoc, diag::warn_bool_switch_condition)
  683. << CondExpr->getSourceRange();
  684. }
  685. }
  686. // Get the bitwidth of the switched-on value after promotions. We must
  687. // convert the integer case values to this width before comparison.
  688. bool HasDependentValue
  689. = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
  690. unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
  691. bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
  692. // Get the width and signedness that the condition might actually have, for
  693. // warning purposes.
  694. // FIXME: Grab an IntRange for the condition rather than using the unpromoted
  695. // type.
  696. unsigned CondWidthBeforePromotion
  697. = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
  698. bool CondIsSignedBeforePromotion
  699. = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
  700. // Accumulate all of the case values in a vector so that we can sort them
  701. // and detect duplicates. This vector contains the APInt for the case after
  702. // it has been converted to the condition type.
  703. typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
  704. CaseValsTy CaseVals;
  705. // Keep track of any GNU case ranges we see. The APSInt is the low value.
  706. typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
  707. CaseRangesTy CaseRanges;
  708. DefaultStmt *TheDefaultStmt = nullptr;
  709. bool CaseListIsErroneous = false;
  710. for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
  711. SC = SC->getNextSwitchCase()) {
  712. if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
  713. if (TheDefaultStmt) {
  714. Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
  715. Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
  716. // FIXME: Remove the default statement from the switch block so that
  717. // we'll return a valid AST. This requires recursing down the AST and
  718. // finding it, not something we are set up to do right now. For now,
  719. // just lop the entire switch stmt out of the AST.
  720. CaseListIsErroneous = true;
  721. }
  722. TheDefaultStmt = DS;
  723. } else {
  724. CaseStmt *CS = cast<CaseStmt>(SC);
  725. Expr *Lo = CS->getLHS();
  726. if (Lo->isTypeDependent() || Lo->isValueDependent()) {
  727. HasDependentValue = true;
  728. break;
  729. }
  730. llvm::APSInt LoVal;
  731. if (getLangOpts().CPlusPlus11 || getLangOpts().HLSLVersion >= 2017) {
  732. // C++11 [stmt.switch]p2: the constant-expression shall be a converted
  733. // constant expression of the promoted type of the switch condition.
  734. ExprResult ConvLo =
  735. CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
  736. if (ConvLo.isInvalid()) {
  737. CaseListIsErroneous = true;
  738. continue;
  739. }
  740. Lo = ConvLo.get();
  741. } else {
  742. // We already verified that the expression has a i-c-e value (C99
  743. // 6.8.4.2p3) - get that value now.
  744. LoVal = Lo->EvaluateKnownConstInt(Context);
  745. // If the LHS is not the same type as the condition, insert an implicit
  746. // cast.
  747. Lo = DefaultLvalueConversion(Lo).get();
  748. Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
  749. }
  750. // Check the unconverted value is within the range of possible values of
  751. // the switch expression.
  752. checkCaseValue(*this, Lo->getLocStart(), LoVal,
  753. CondWidthBeforePromotion, CondIsSignedBeforePromotion);
  754. // Convert the value to the same width/sign as the condition.
  755. AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
  756. CS->setLHS(Lo);
  757. // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
  758. if (CS->getRHS()) {
  759. if (CS->getRHS()->isTypeDependent() ||
  760. CS->getRHS()->isValueDependent()) {
  761. HasDependentValue = true;
  762. break;
  763. }
  764. CaseRanges.push_back(std::make_pair(LoVal, CS));
  765. } else
  766. CaseVals.push_back(std::make_pair(LoVal, CS));
  767. }
  768. }
  769. if (!HasDependentValue) {
  770. // If we don't have a default statement, check whether the
  771. // condition is constant.
  772. llvm::APSInt ConstantCondValue;
  773. bool HasConstantCond = false;
  774. if (!HasDependentValue && !TheDefaultStmt) {
  775. HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
  776. Expr::SE_AllowSideEffects);
  777. assert(!HasConstantCond ||
  778. (ConstantCondValue.getBitWidth() == CondWidth &&
  779. ConstantCondValue.isSigned() == CondIsSigned));
  780. }
  781. bool ShouldCheckConstantCond = HasConstantCond;
  782. // Sort all the scalar case values so we can easily detect duplicates.
  783. std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
  784. if (!CaseVals.empty()) {
  785. for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
  786. if (ShouldCheckConstantCond &&
  787. CaseVals[i].first == ConstantCondValue)
  788. ShouldCheckConstantCond = false;
  789. if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
  790. // If we have a duplicate, report it.
  791. // First, determine if either case value has a name
  792. StringRef PrevString, CurrString;
  793. Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
  794. Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
  795. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
  796. PrevString = DeclRef->getDecl()->getName();
  797. }
  798. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
  799. CurrString = DeclRef->getDecl()->getName();
  800. }
  801. SmallString<16> CaseValStr;
  802. CaseVals[i-1].first.toString(CaseValStr);
  803. if (PrevString == CurrString)
  804. Diag(CaseVals[i].second->getLHS()->getLocStart(),
  805. diag::err_duplicate_case) <<
  806. (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
  807. else
  808. Diag(CaseVals[i].second->getLHS()->getLocStart(),
  809. diag::err_duplicate_case_differing_expr) <<
  810. (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
  811. (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
  812. CaseValStr;
  813. Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
  814. diag::note_duplicate_case_prev);
  815. // FIXME: We really want to remove the bogus case stmt from the
  816. // substmt, but we have no way to do this right now.
  817. CaseListIsErroneous = true;
  818. }
  819. }
  820. }
  821. // Detect duplicate case ranges, which usually don't exist at all in
  822. // the first place.
  823. if (!CaseRanges.empty()) {
  824. // Sort all the case ranges by their low value so we can easily detect
  825. // overlaps between ranges.
  826. std::stable_sort(CaseRanges.begin(), CaseRanges.end());
  827. // Scan the ranges, computing the high values and removing empty ranges.
  828. std::vector<llvm::APSInt> HiVals;
  829. for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
  830. llvm::APSInt &LoVal = CaseRanges[i].first;
  831. CaseStmt *CR = CaseRanges[i].second;
  832. Expr *Hi = CR->getRHS();
  833. llvm::APSInt HiVal;
  834. if (getLangOpts().CPlusPlus11) {
  835. // C++11 [stmt.switch]p2: the constant-expression shall be a converted
  836. // constant expression of the promoted type of the switch condition.
  837. ExprResult ConvHi =
  838. CheckConvertedConstantExpression(Hi, CondType, HiVal,
  839. CCEK_CaseValue);
  840. if (ConvHi.isInvalid()) {
  841. CaseListIsErroneous = true;
  842. continue;
  843. }
  844. Hi = ConvHi.get();
  845. } else {
  846. HiVal = Hi->EvaluateKnownConstInt(Context);
  847. // If the RHS is not the same type as the condition, insert an
  848. // implicit cast.
  849. Hi = DefaultLvalueConversion(Hi).get();
  850. Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
  851. }
  852. // Check the unconverted value is within the range of possible values of
  853. // the switch expression.
  854. checkCaseValue(*this, Hi->getLocStart(), HiVal,
  855. CondWidthBeforePromotion, CondIsSignedBeforePromotion);
  856. // Convert the value to the same width/sign as the condition.
  857. AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
  858. CR->setRHS(Hi);
  859. // If the low value is bigger than the high value, the case is empty.
  860. if (LoVal > HiVal) {
  861. Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
  862. << SourceRange(CR->getLHS()->getLocStart(),
  863. Hi->getLocEnd());
  864. CaseRanges.erase(CaseRanges.begin()+i);
  865. --i, --e;
  866. continue;
  867. }
  868. if (ShouldCheckConstantCond &&
  869. LoVal <= ConstantCondValue &&
  870. ConstantCondValue <= HiVal)
  871. ShouldCheckConstantCond = false;
  872. HiVals.push_back(HiVal);
  873. }
  874. // Rescan the ranges, looking for overlap with singleton values and other
  875. // ranges. Since the range list is sorted, we only need to compare case
  876. // ranges with their neighbors.
  877. for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
  878. llvm::APSInt &CRLo = CaseRanges[i].first;
  879. llvm::APSInt &CRHi = HiVals[i];
  880. CaseStmt *CR = CaseRanges[i].second;
  881. // Check to see whether the case range overlaps with any
  882. // singleton cases.
  883. CaseStmt *OverlapStmt = nullptr;
  884. llvm::APSInt OverlapVal(32);
  885. // Find the smallest value >= the lower bound. If I is in the
  886. // case range, then we have overlap.
  887. CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
  888. CaseVals.end(), CRLo,
  889. CaseCompareFunctor());
  890. if (I != CaseVals.end() && I->first < CRHi) {
  891. OverlapVal = I->first; // Found overlap with scalar.
  892. OverlapStmt = I->second;
  893. }
  894. // Find the smallest value bigger than the upper bound.
  895. I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
  896. if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
  897. OverlapVal = (I-1)->first; // Found overlap with scalar.
  898. OverlapStmt = (I-1)->second;
  899. }
  900. // Check to see if this case stmt overlaps with the subsequent
  901. // case range.
  902. if (i && CRLo <= HiVals[i-1]) {
  903. OverlapVal = HiVals[i-1]; // Found overlap with range.
  904. OverlapStmt = CaseRanges[i-1].second;
  905. }
  906. if (OverlapStmt) {
  907. // If we have a duplicate, report it.
  908. Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
  909. << OverlapVal.toString(10);
  910. Diag(OverlapStmt->getLHS()->getLocStart(),
  911. diag::note_duplicate_case_prev);
  912. // FIXME: We really want to remove the bogus case stmt from the
  913. // substmt, but we have no way to do this right now.
  914. CaseListIsErroneous = true;
  915. }
  916. }
  917. }
  918. // Complain if we have a constant condition and we didn't find a match.
  919. if (!CaseListIsErroneous && ShouldCheckConstantCond) {
  920. // TODO: it would be nice if we printed enums as enums, chars as
  921. // chars, etc.
  922. Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
  923. << ConstantCondValue.toString(10)
  924. << CondExpr->getSourceRange();
  925. }
  926. // Check to see if switch is over an Enum and handles all of its
  927. // values. We only issue a warning if there is not 'default:', but
  928. // we still do the analysis to preserve this information in the AST
  929. // (which can be used by flow-based analyes).
  930. //
  931. const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
  932. // If switch has default case, then ignore it.
  933. if (!CaseListIsErroneous && !HasConstantCond && ET) {
  934. const EnumDecl *ED = ET->getDecl();
  935. EnumValsTy EnumVals;
  936. // Gather all enum values, set their type and sort them,
  937. // allowing easier comparison with CaseVals.
  938. for (auto *EDI : ED->enumerators()) {
  939. llvm::APSInt Val = EDI->getInitVal();
  940. AdjustAPSInt(Val, CondWidth, CondIsSigned);
  941. EnumVals.push_back(std::make_pair(Val, EDI));
  942. }
  943. std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
  944. auto EI = EnumVals.begin(), EIEnd =
  945. std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
  946. // See which case values aren't in enum.
  947. for (CaseValsTy::const_iterator CI = CaseVals.begin();
  948. CI != CaseVals.end(); CI++) {
  949. Expr *CaseExpr = CI->second->getLHS();
  950. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  951. CI->first))
  952. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  953. << CondTypeBeforePromotion;
  954. }
  955. // See which of case ranges aren't in enum
  956. EI = EnumVals.begin();
  957. for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
  958. RI != CaseRanges.end(); RI++) {
  959. Expr *CaseExpr = RI->second->getLHS();
  960. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  961. RI->first))
  962. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  963. << CondTypeBeforePromotion;
  964. llvm::APSInt Hi =
  965. RI->second->getRHS()->EvaluateKnownConstInt(Context);
  966. AdjustAPSInt(Hi, CondWidth, CondIsSigned);
  967. CaseExpr = RI->second->getRHS();
  968. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  969. Hi))
  970. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  971. << CondTypeBeforePromotion;
  972. }
  973. // Check which enum vals aren't in switch
  974. auto CI = CaseVals.begin();
  975. auto RI = CaseRanges.begin();
  976. bool hasCasesNotInSwitch = false;
  977. SmallVector<DeclarationName,8> UnhandledNames;
  978. for (EI = EnumVals.begin(); EI != EIEnd; EI++){
  979. // Drop unneeded case values
  980. while (CI != CaseVals.end() && CI->first < EI->first)
  981. CI++;
  982. if (CI != CaseVals.end() && CI->first == EI->first)
  983. continue;
  984. // Drop unneeded case ranges
  985. for (; RI != CaseRanges.end(); RI++) {
  986. llvm::APSInt Hi =
  987. RI->second->getRHS()->EvaluateKnownConstInt(Context);
  988. AdjustAPSInt(Hi, CondWidth, CondIsSigned);
  989. if (EI->first <= Hi)
  990. break;
  991. }
  992. if (RI == CaseRanges.end() || EI->first < RI->first) {
  993. hasCasesNotInSwitch = true;
  994. UnhandledNames.push_back(EI->second->getDeclName());
  995. }
  996. }
  997. if (TheDefaultStmt && UnhandledNames.empty())
  998. Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
  999. // Produce a nice diagnostic if multiple values aren't handled.
  1000. if (!UnhandledNames.empty()) {
  1001. DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
  1002. TheDefaultStmt ? diag::warn_def_missing_case
  1003. : diag::warn_missing_case)
  1004. << (int)UnhandledNames.size();
  1005. for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
  1006. I != E; ++I)
  1007. DB << UnhandledNames[I];
  1008. }
  1009. if (!hasCasesNotInSwitch)
  1010. SS->setAllEnumCasesCovered();
  1011. }
  1012. }
  1013. if (BodyStmt)
  1014. DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
  1015. diag::warn_empty_switch_body);
  1016. // FIXME: If the case list was broken is some way, we don't have a good system
  1017. // to patch it up. Instead, just return the whole substmt as broken.
  1018. if (CaseListIsErroneous)
  1019. return StmtError();
  1020. return SS;
  1021. }
  1022. void
  1023. Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
  1024. Expr *SrcExpr) {
  1025. if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
  1026. return;
  1027. if (const EnumType *ET = DstType->getAs<EnumType>())
  1028. if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
  1029. SrcType->isIntegerType()) {
  1030. if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
  1031. SrcExpr->isIntegerConstantExpr(Context)) {
  1032. // Get the bitwidth of the enum value before promotions.
  1033. unsigned DstWidth = Context.getIntWidth(DstType);
  1034. bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
  1035. llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
  1036. AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
  1037. const EnumDecl *ED = ET->getDecl();
  1038. if (ED->hasAttr<FlagEnumAttr>()) {
  1039. if (!IsValueInFlagEnum(ED, RhsVal, true))
  1040. Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
  1041. << DstType.getUnqualifiedType();
  1042. } else {
  1043. typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
  1044. EnumValsTy;
  1045. EnumValsTy EnumVals;
  1046. // Gather all enum values, set their type and sort them,
  1047. // allowing easier comparison with rhs constant.
  1048. for (auto *EDI : ED->enumerators()) {
  1049. llvm::APSInt Val = EDI->getInitVal();
  1050. AdjustAPSInt(Val, DstWidth, DstIsSigned);
  1051. EnumVals.push_back(std::make_pair(Val, EDI));
  1052. }
  1053. if (EnumVals.empty())
  1054. return;
  1055. std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
  1056. EnumValsTy::iterator EIend =
  1057. std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
  1058. // See which values aren't in the enum.
  1059. EnumValsTy::const_iterator EI = EnumVals.begin();
  1060. while (EI != EIend && EI->first < RhsVal)
  1061. EI++;
  1062. if (EI == EIend || EI->first != RhsVal) {
  1063. Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
  1064. << DstType.getUnqualifiedType();
  1065. }
  1066. }
  1067. }
  1068. }
  1069. }
  1070. StmtResult
  1071. Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
  1072. Decl *CondVar, Stmt *Body) {
  1073. ExprResult CondResult(Cond.release());
  1074. VarDecl *ConditionVar = nullptr;
  1075. if (CondVar) {
  1076. ConditionVar = cast<VarDecl>(CondVar);
  1077. CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
  1078. CondResult = ActOnFinishFullExpr(CondResult.get(), WhileLoc);
  1079. if (CondResult.isInvalid())
  1080. return StmtError();
  1081. }
  1082. Expr *ConditionExpr = CondResult.get();
  1083. if (!ConditionExpr)
  1084. return StmtError();
  1085. // HLSL Change Begin.
  1086. hlsl::DiagnoseControlFlowConditionForHLSL(this, ConditionExpr, "while");
  1087. // HLSL Change End.
  1088. CheckBreakContinueBinding(ConditionExpr);
  1089. DiagnoseUnusedExprResult(Body);
  1090. if (isa<NullStmt>(Body))
  1091. getCurCompoundScope().setHasEmptyLoopBodies();
  1092. return new (Context)
  1093. WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
  1094. }
  1095. StmtResult
  1096. Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
  1097. SourceLocation WhileLoc, SourceLocation CondLParen,
  1098. Expr *Cond, SourceLocation CondRParen) {
  1099. assert(Cond && "ActOnDoStmt(): missing expression");
  1100. CheckBreakContinueBinding(Cond);
  1101. ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
  1102. if (CondResult.isInvalid())
  1103. return StmtError();
  1104. Cond = CondResult.get();
  1105. CondResult = ActOnFinishFullExpr(Cond, DoLoc);
  1106. if (CondResult.isInvalid())
  1107. return StmtError();
  1108. Cond = CondResult.get();
  1109. // HLSL Change Begin.
  1110. if (Cond) {
  1111. hlsl::DiagnoseControlFlowConditionForHLSL(this, Cond, "do-while");
  1112. }
  1113. // HLSL Change End.
  1114. DiagnoseUnusedExprResult(Body);
  1115. return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
  1116. }
  1117. namespace {
  1118. // This visitor will traverse a conditional statement and store all
  1119. // the evaluated decls into a vector. Simple is set to true if none
  1120. // of the excluded constructs are used.
  1121. class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
  1122. llvm::SmallPtrSetImpl<VarDecl*> &Decls;
  1123. SmallVectorImpl<SourceRange> &Ranges;
  1124. bool Simple;
  1125. public:
  1126. typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
  1127. DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
  1128. SmallVectorImpl<SourceRange> &Ranges) :
  1129. Inherited(S.Context),
  1130. Decls(Decls),
  1131. Ranges(Ranges),
  1132. Simple(true) {}
  1133. bool isSimple() { return Simple; }
  1134. // Replaces the method in EvaluatedExprVisitor.
  1135. void VisitMemberExpr(MemberExpr* E) {
  1136. Simple = false;
  1137. }
  1138. // Any Stmt not whitelisted will cause the condition to be marked complex.
  1139. void VisitStmt(Stmt *S) {
  1140. Simple = false;
  1141. }
  1142. void VisitBinaryOperator(BinaryOperator *E) {
  1143. Visit(E->getLHS());
  1144. Visit(E->getRHS());
  1145. }
  1146. void VisitCastExpr(CastExpr *E) {
  1147. Visit(E->getSubExpr());
  1148. }
  1149. void VisitUnaryOperator(UnaryOperator *E) {
  1150. // Skip checking conditionals with derefernces.
  1151. if (E->getOpcode() == UO_Deref)
  1152. Simple = false;
  1153. else
  1154. Visit(E->getSubExpr());
  1155. }
  1156. void VisitConditionalOperator(ConditionalOperator *E) {
  1157. Visit(E->getCond());
  1158. Visit(E->getTrueExpr());
  1159. Visit(E->getFalseExpr());
  1160. }
  1161. void VisitParenExpr(ParenExpr *E) {
  1162. Visit(E->getSubExpr());
  1163. }
  1164. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  1165. Visit(E->getOpaqueValue()->getSourceExpr());
  1166. Visit(E->getFalseExpr());
  1167. }
  1168. void VisitIntegerLiteral(IntegerLiteral *E) { }
  1169. void VisitFloatingLiteral(FloatingLiteral *E) { }
  1170. void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
  1171. void VisitCharacterLiteral(CharacterLiteral *E) { }
  1172. void VisitGNUNullExpr(GNUNullExpr *E) { }
  1173. void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
  1174. void VisitDeclRefExpr(DeclRefExpr *E) {
  1175. VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
  1176. if (!VD) return;
  1177. Ranges.push_back(E->getSourceRange());
  1178. Decls.insert(VD);
  1179. }
  1180. }; // end class DeclExtractor
  1181. // DeclMatcher checks to see if the decls are used in a non-evauluated
  1182. // context.
  1183. class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
  1184. llvm::SmallPtrSetImpl<VarDecl*> &Decls;
  1185. bool FoundDecl;
  1186. public:
  1187. typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
  1188. DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
  1189. Stmt *Statement) :
  1190. Inherited(S.Context), Decls(Decls), FoundDecl(false) {
  1191. if (!Statement) return;
  1192. Visit(Statement);
  1193. }
  1194. void VisitReturnStmt(ReturnStmt *S) {
  1195. FoundDecl = true;
  1196. }
  1197. void VisitBreakStmt(BreakStmt *S) {
  1198. FoundDecl = true;
  1199. }
  1200. void VisitGotoStmt(GotoStmt *S) {
  1201. FoundDecl = true;
  1202. }
  1203. void VisitCastExpr(CastExpr *E) {
  1204. if (E->getCastKind() == CK_LValueToRValue)
  1205. CheckLValueToRValueCast(E->getSubExpr());
  1206. else
  1207. Visit(E->getSubExpr());
  1208. }
  1209. void CheckLValueToRValueCast(Expr *E) {
  1210. E = E->IgnoreParenImpCasts();
  1211. if (isa<DeclRefExpr>(E)) {
  1212. return;
  1213. }
  1214. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  1215. Visit(CO->getCond());
  1216. CheckLValueToRValueCast(CO->getTrueExpr());
  1217. CheckLValueToRValueCast(CO->getFalseExpr());
  1218. return;
  1219. }
  1220. if (BinaryConditionalOperator *BCO =
  1221. dyn_cast<BinaryConditionalOperator>(E)) {
  1222. CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
  1223. CheckLValueToRValueCast(BCO->getFalseExpr());
  1224. return;
  1225. }
  1226. Visit(E);
  1227. }
  1228. void VisitDeclRefExpr(DeclRefExpr *E) {
  1229. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  1230. if (Decls.count(VD))
  1231. FoundDecl = true;
  1232. }
  1233. bool FoundDeclInUse() { return FoundDecl; }
  1234. }; // end class DeclMatcher
  1235. void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
  1236. Expr *Third, Stmt *Body) {
  1237. // Condition is empty
  1238. if (!Second) return;
  1239. if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
  1240. Second->getLocStart()))
  1241. return;
  1242. PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
  1243. llvm::SmallPtrSet<VarDecl*, 8> Decls;
  1244. SmallVector<SourceRange, 10> Ranges;
  1245. DeclExtractor DE(S, Decls, Ranges);
  1246. DE.Visit(Second);
  1247. // Don't analyze complex conditionals.
  1248. if (!DE.isSimple()) return;
  1249. // No decls found.
  1250. if (Decls.size() == 0) return;
  1251. // Don't warn on volatile, static, or global variables.
  1252. for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
  1253. E = Decls.end();
  1254. I != E; ++I)
  1255. if ((*I)->getType().isVolatileQualified() ||
  1256. (*I)->hasGlobalStorage()) return;
  1257. if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
  1258. DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
  1259. DeclMatcher(S, Decls, Body).FoundDeclInUse())
  1260. return;
  1261. // Load decl names into diagnostic.
  1262. if (Decls.size() > 4)
  1263. PDiag << 0;
  1264. else {
  1265. PDiag << Decls.size();
  1266. for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
  1267. E = Decls.end();
  1268. I != E; ++I)
  1269. PDiag << (*I)->getDeclName();
  1270. }
  1271. // Load SourceRanges into diagnostic if there is room.
  1272. // Otherwise, load the SourceRange of the conditional expression.
  1273. if (Ranges.size() <= PartialDiagnostic::MaxArguments)
  1274. for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
  1275. E = Ranges.end();
  1276. I != E; ++I)
  1277. PDiag << *I;
  1278. else
  1279. PDiag << Second->getSourceRange();
  1280. S.Diag(Ranges.begin()->getBegin(), PDiag);
  1281. }
  1282. // If Statement is an incemement or decrement, return true and sets the
  1283. // variables Increment and DRE.
  1284. bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
  1285. DeclRefExpr *&DRE) {
  1286. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
  1287. switch (UO->getOpcode()) {
  1288. default: return false;
  1289. case UO_PostInc:
  1290. case UO_PreInc:
  1291. Increment = true;
  1292. break;
  1293. case UO_PostDec:
  1294. case UO_PreDec:
  1295. Increment = false;
  1296. break;
  1297. }
  1298. DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
  1299. return DRE;
  1300. }
  1301. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
  1302. FunctionDecl *FD = Call->getDirectCallee();
  1303. if (!FD || !FD->isOverloadedOperator()) return false;
  1304. switch (FD->getOverloadedOperator()) {
  1305. default: return false;
  1306. case OO_PlusPlus:
  1307. Increment = true;
  1308. break;
  1309. case OO_MinusMinus:
  1310. Increment = false;
  1311. break;
  1312. }
  1313. DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
  1314. return DRE;
  1315. }
  1316. return false;
  1317. }
  1318. // A visitor to determine if a continue or break statement is a
  1319. // subexpression.
  1320. class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
  1321. SourceLocation BreakLoc;
  1322. SourceLocation ContinueLoc;
  1323. public:
  1324. BreakContinueFinder(Sema &S, Stmt* Body) :
  1325. Inherited(S.Context) {
  1326. Visit(Body);
  1327. }
  1328. typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
  1329. void VisitContinueStmt(ContinueStmt* E) {
  1330. ContinueLoc = E->getContinueLoc();
  1331. }
  1332. void VisitBreakStmt(BreakStmt* E) {
  1333. BreakLoc = E->getBreakLoc();
  1334. }
  1335. bool ContinueFound() { return ContinueLoc.isValid(); }
  1336. bool BreakFound() { return BreakLoc.isValid(); }
  1337. SourceLocation GetContinueLoc() { return ContinueLoc; }
  1338. SourceLocation GetBreakLoc() { return BreakLoc; }
  1339. }; // end class BreakContinueFinder
  1340. // Emit a warning when a loop increment/decrement appears twice per loop
  1341. // iteration. The conditions which trigger this warning are:
  1342. // 1) The last statement in the loop body and the third expression in the
  1343. // for loop are both increment or both decrement of the same variable
  1344. // 2) No continue statements in the loop body.
  1345. void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
  1346. // Return when there is nothing to check.
  1347. if (!Body || !Third) return;
  1348. if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
  1349. Third->getLocStart()))
  1350. return;
  1351. // Get the last statement from the loop body.
  1352. CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
  1353. if (!CS || CS->body_empty()) return;
  1354. Stmt *LastStmt = CS->body_back();
  1355. if (!LastStmt) return;
  1356. bool LoopIncrement, LastIncrement;
  1357. DeclRefExpr *LoopDRE, *LastDRE;
  1358. if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
  1359. if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
  1360. // Check that the two statements are both increments or both decrements
  1361. // on the same variable.
  1362. if (LoopIncrement != LastIncrement ||
  1363. LoopDRE->getDecl() != LastDRE->getDecl()) return;
  1364. if (BreakContinueFinder(S, Body).ContinueFound()) return;
  1365. S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
  1366. << LastDRE->getDecl() << LastIncrement;
  1367. S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
  1368. << LoopIncrement;
  1369. }
  1370. } // end namespace
  1371. void Sema::CheckBreakContinueBinding(Expr *E) {
  1372. if (!E || getLangOpts().CPlusPlus)
  1373. return;
  1374. BreakContinueFinder BCFinder(*this, E);
  1375. Scope *BreakParent = CurScope->getBreakParent();
  1376. if (BCFinder.BreakFound() && BreakParent) {
  1377. if (BreakParent->getFlags() & Scope::SwitchScope) {
  1378. Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
  1379. } else {
  1380. Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
  1381. << "break";
  1382. }
  1383. } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
  1384. Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
  1385. << "continue";
  1386. }
  1387. }
  1388. StmtResult
  1389. Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
  1390. Stmt *First, FullExprArg second, Decl *secondVar,
  1391. FullExprArg third,
  1392. SourceLocation RParenLoc, Stmt *Body) {
  1393. if (!getLangOpts().CPlusPlus) {
  1394. if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
  1395. // C99 6.8.5p3: The declaration part of a 'for' statement shall only
  1396. // declare identifiers for objects having storage class 'auto' or
  1397. // 'register'.
  1398. for (auto *DI : DS->decls()) {
  1399. VarDecl *VD = dyn_cast<VarDecl>(DI);
  1400. if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
  1401. VD = nullptr;
  1402. if (!VD) {
  1403. Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
  1404. DI->setInvalidDecl();
  1405. }
  1406. }
  1407. }
  1408. }
  1409. CheckBreakContinueBinding(second.get());
  1410. CheckBreakContinueBinding(third.get());
  1411. CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
  1412. CheckForRedundantIteration(*this, third.get(), Body);
  1413. ExprResult SecondResult(second.release());
  1414. VarDecl *ConditionVar = nullptr;
  1415. if (secondVar) {
  1416. ConditionVar = cast<VarDecl>(secondVar);
  1417. SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
  1418. SecondResult = ActOnFinishFullExpr(SecondResult.get(), ForLoc);
  1419. if (SecondResult.isInvalid())
  1420. return StmtError();
  1421. }
  1422. // HLSL Change Begin.
  1423. Expr *Cond = SecondResult.get();
  1424. if (Cond) {
  1425. hlsl::DiagnoseControlFlowConditionForHLSL(this, Cond, "for");
  1426. }
  1427. // HLSL Change End.
  1428. Expr *Third = third.release().getAs<Expr>();
  1429. DiagnoseUnusedExprResult(First);
  1430. DiagnoseUnusedExprResult(Third);
  1431. DiagnoseUnusedExprResult(Body);
  1432. if (isa<NullStmt>(Body))
  1433. getCurCompoundScope().setHasEmptyLoopBodies();
  1434. return new (Context) ForStmt(Context, First, Cond, ConditionVar,
  1435. Third, Body, ForLoc, LParenLoc, RParenLoc);
  1436. }
  1437. /// In an Objective C collection iteration statement:
  1438. /// for (x in y)
  1439. /// x can be an arbitrary l-value expression. Bind it up as a
  1440. /// full-expression.
  1441. StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
  1442. // Reduce placeholder expressions here. Note that this rejects the
  1443. // use of pseudo-object l-values in this position.
  1444. ExprResult result = CheckPlaceholderExpr(E);
  1445. if (result.isInvalid()) return StmtError();
  1446. E = result.get();
  1447. ExprResult FullExpr = ActOnFinishFullExpr(E);
  1448. if (FullExpr.isInvalid())
  1449. return StmtError();
  1450. return StmtResult(static_cast<Stmt*>(FullExpr.get()));
  1451. }
  1452. ExprResult
  1453. Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
  1454. if (!collection)
  1455. return ExprError();
  1456. ExprResult result = CorrectDelayedTyposInExpr(collection);
  1457. if (!result.isUsable())
  1458. return ExprError();
  1459. collection = result.get();
  1460. // Bail out early if we've got a type-dependent expression.
  1461. if (collection->isTypeDependent()) return collection;
  1462. // Perform normal l-value conversion.
  1463. result = DefaultFunctionArrayLvalueConversion(collection);
  1464. if (result.isInvalid())
  1465. return ExprError();
  1466. collection = result.get();
  1467. // The operand needs to have object-pointer type.
  1468. // TODO: should we do a contextual conversion?
  1469. const ObjCObjectPointerType *pointerType =
  1470. collection->getType()->getAs<ObjCObjectPointerType>();
  1471. if (!pointerType)
  1472. return Diag(forLoc, diag::err_collection_expr_type)
  1473. << collection->getType() << collection->getSourceRange();
  1474. // Check that the operand provides
  1475. // - countByEnumeratingWithState:objects:count:
  1476. const ObjCObjectType *objectType = pointerType->getObjectType();
  1477. ObjCInterfaceDecl *iface = objectType->getInterface();
  1478. // If we have a forward-declared type, we can't do this check.
  1479. // Under ARC, it is an error not to have a forward-declared class.
  1480. if (iface &&
  1481. RequireCompleteType(forLoc, QualType(objectType, 0),
  1482. getLangOpts().ObjCAutoRefCount
  1483. ? diag::err_arc_collection_forward
  1484. : 0,
  1485. collection)) {
  1486. // Otherwise, if we have any useful type information, check that
  1487. // the type declares the appropriate method.
  1488. } else if (iface || !objectType->qual_empty()) {
  1489. IdentifierInfo *selectorIdents[] = {
  1490. &Context.Idents.get("countByEnumeratingWithState"),
  1491. &Context.Idents.get("objects"),
  1492. &Context.Idents.get("count")
  1493. };
  1494. Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
  1495. ObjCMethodDecl *method = nullptr;
  1496. // If there's an interface, look in both the public and private APIs.
  1497. if (iface) {
  1498. method = iface->lookupInstanceMethod(selector);
  1499. if (!method) method = iface->lookupPrivateMethod(selector);
  1500. }
  1501. // Also check protocol qualifiers.
  1502. if (!method)
  1503. method = LookupMethodInQualifiedType(selector, pointerType,
  1504. /*instance*/ true);
  1505. // If we didn't find it anywhere, give up.
  1506. if (!method) {
  1507. Diag(forLoc, diag::warn_collection_expr_type)
  1508. << collection->getType() << selector << collection->getSourceRange();
  1509. }
  1510. // TODO: check for an incompatible signature?
  1511. }
  1512. // Wrap up any cleanups in the expression.
  1513. return collection;
  1514. }
  1515. StmtResult
  1516. Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
  1517. Stmt *First, Expr *collection,
  1518. SourceLocation RParenLoc) {
  1519. ExprResult CollectionExprResult =
  1520. CheckObjCForCollectionOperand(ForLoc, collection);
  1521. if (First) {
  1522. QualType FirstType;
  1523. if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
  1524. if (!DS->isSingleDecl())
  1525. return StmtError(Diag((*DS->decl_begin())->getLocation(),
  1526. diag::err_toomany_element_decls));
  1527. VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
  1528. if (!D || D->isInvalidDecl())
  1529. return StmtError();
  1530. FirstType = D->getType();
  1531. // C99 6.8.5p3: The declaration part of a 'for' statement shall only
  1532. // declare identifiers for objects having storage class 'auto' or
  1533. // 'register'.
  1534. if (!D->hasLocalStorage())
  1535. return StmtError(Diag(D->getLocation(),
  1536. diag::err_non_local_variable_decl_in_for));
  1537. // If the type contained 'auto', deduce the 'auto' to 'id'.
  1538. if (FirstType->getContainedAutoType()) {
  1539. OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
  1540. VK_RValue);
  1541. Expr *DeducedInit = &OpaqueId;
  1542. if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
  1543. DAR_Failed)
  1544. DiagnoseAutoDeductionFailure(D, DeducedInit);
  1545. if (FirstType.isNull()) {
  1546. D->setInvalidDecl();
  1547. return StmtError();
  1548. }
  1549. D->setType(FirstType);
  1550. if (ActiveTemplateInstantiations.empty()) {
  1551. SourceLocation Loc =
  1552. D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
  1553. Diag(Loc, diag::warn_auto_var_is_id)
  1554. << D->getDeclName();
  1555. }
  1556. }
  1557. } else {
  1558. Expr *FirstE = cast<Expr>(First);
  1559. if (!FirstE->isTypeDependent() && !FirstE->isLValue())
  1560. return StmtError(Diag(First->getLocStart(),
  1561. diag::err_selector_element_not_lvalue)
  1562. << First->getSourceRange());
  1563. FirstType = static_cast<Expr*>(First)->getType();
  1564. if (FirstType.isConstQualified())
  1565. Diag(ForLoc, diag::err_selector_element_const_type)
  1566. << FirstType << First->getSourceRange();
  1567. }
  1568. if (!FirstType->isDependentType() &&
  1569. !FirstType->isObjCObjectPointerType() &&
  1570. !FirstType->isBlockPointerType())
  1571. return StmtError(Diag(ForLoc, diag::err_selector_element_type)
  1572. << FirstType << First->getSourceRange());
  1573. }
  1574. if (CollectionExprResult.isInvalid())
  1575. return StmtError();
  1576. CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
  1577. if (CollectionExprResult.isInvalid())
  1578. return StmtError();
  1579. return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
  1580. nullptr, ForLoc, RParenLoc);
  1581. }
  1582. /// Finish building a variable declaration for a for-range statement.
  1583. /// \return true if an error occurs.
  1584. static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
  1585. SourceLocation Loc, int DiagID) {
  1586. if (Decl->getType()->isUndeducedType()) {
  1587. ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
  1588. if (!Res.isUsable()) {
  1589. Decl->setInvalidDecl();
  1590. return true;
  1591. }
  1592. Init = Res.get();
  1593. }
  1594. // Deduce the type for the iterator variable now rather than leaving it to
  1595. // AddInitializerToDecl, so we can produce a more suitable diagnostic.
  1596. QualType InitType;
  1597. if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
  1598. SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
  1599. Sema::DAR_Failed)
  1600. SemaRef.Diag(Loc, DiagID) << Init->getType();
  1601. if (InitType.isNull()) {
  1602. Decl->setInvalidDecl();
  1603. return true;
  1604. }
  1605. Decl->setType(InitType);
  1606. // In ARC, infer lifetime.
  1607. // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
  1608. // we're doing the equivalent of fast iteration.
  1609. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  1610. SemaRef.inferObjCARCLifetime(Decl))
  1611. Decl->setInvalidDecl();
  1612. SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
  1613. /*TypeMayContainAuto=*/false);
  1614. SemaRef.FinalizeDeclaration(Decl);
  1615. SemaRef.CurContext->addHiddenDecl(Decl);
  1616. return false;
  1617. }
  1618. namespace {
  1619. /// Produce a note indicating which begin/end function was implicitly called
  1620. /// by a C++11 for-range statement. This is often not obvious from the code,
  1621. /// nor from the diagnostics produced when analysing the implicit expressions
  1622. /// required in a for-range statement.
  1623. void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
  1624. Sema::BeginEndFunction BEF) {
  1625. CallExpr *CE = dyn_cast<CallExpr>(E);
  1626. if (!CE)
  1627. return;
  1628. FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  1629. if (!D)
  1630. return;
  1631. SourceLocation Loc = D->getLocation();
  1632. std::string Description;
  1633. bool IsTemplate = false;
  1634. if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
  1635. Description = SemaRef.getTemplateArgumentBindingsText(
  1636. FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
  1637. IsTemplate = true;
  1638. }
  1639. SemaRef.Diag(Loc, diag::note_for_range_begin_end)
  1640. << BEF << IsTemplate << Description << E->getType();
  1641. }
  1642. /// Build a variable declaration for a for-range statement.
  1643. VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
  1644. QualType Type, const char *Name) {
  1645. DeclContext *DC = SemaRef.CurContext;
  1646. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1647. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1648. VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
  1649. TInfo, SC_None);
  1650. Decl->setImplicit();
  1651. return Decl;
  1652. }
  1653. }
  1654. static bool ObjCEnumerationCollection(Expr *Collection) {
  1655. return !Collection->isTypeDependent()
  1656. && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
  1657. }
  1658. /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
  1659. ///
  1660. /// C++11 [stmt.ranged]:
  1661. /// A range-based for statement is equivalent to
  1662. ///
  1663. /// {
  1664. /// auto && __range = range-init;
  1665. /// for ( auto __begin = begin-expr,
  1666. /// __end = end-expr;
  1667. /// __begin != __end;
  1668. /// ++__begin ) {
  1669. /// for-range-declaration = *__begin;
  1670. /// statement
  1671. /// }
  1672. /// }
  1673. ///
  1674. /// The body of the loop is not available yet, since it cannot be analysed until
  1675. /// we have determined the type of the for-range-declaration.
  1676. StmtResult
  1677. Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
  1678. Stmt *First, SourceLocation ColonLoc, Expr *Range,
  1679. SourceLocation RParenLoc, BuildForRangeKind Kind) {
  1680. if (!First)
  1681. return StmtError();
  1682. if (Range && ObjCEnumerationCollection(Range))
  1683. return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
  1684. DeclStmt *DS = dyn_cast<DeclStmt>(First);
  1685. assert(DS && "first part of for range not a decl stmt");
  1686. if (!DS->isSingleDecl()) {
  1687. Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
  1688. return StmtError();
  1689. }
  1690. Decl *LoopVar = DS->getSingleDecl();
  1691. if (LoopVar->isInvalidDecl() || !Range ||
  1692. DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
  1693. LoopVar->setInvalidDecl();
  1694. return StmtError();
  1695. }
  1696. // Build auto && __range = range-init
  1697. SourceLocation RangeLoc = Range->getLocStart();
  1698. VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
  1699. Context.getAutoRRefDeductType(),
  1700. "__range");
  1701. if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
  1702. diag::err_for_range_deduction_failure)) {
  1703. LoopVar->setInvalidDecl();
  1704. return StmtError();
  1705. }
  1706. // Claim the type doesn't contain auto: we've already done the checking.
  1707. DeclGroupPtrTy RangeGroup =
  1708. BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
  1709. /*TypeMayContainAuto=*/ false);
  1710. StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
  1711. if (RangeDecl.isInvalid()) {
  1712. LoopVar->setInvalidDecl();
  1713. return StmtError();
  1714. }
  1715. return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
  1716. /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
  1717. /*Inc=*/nullptr, DS, RParenLoc, Kind);
  1718. }
  1719. /// \brief Create the initialization, compare, and increment steps for
  1720. /// the range-based for loop expression.
  1721. /// This function does not handle array-based for loops,
  1722. /// which are created in Sema::BuildCXXForRangeStmt.
  1723. ///
  1724. /// \returns a ForRangeStatus indicating success or what kind of error occurred.
  1725. /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
  1726. /// CandidateSet and BEF are set and some non-success value is returned on
  1727. /// failure.
  1728. static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
  1729. Expr *BeginRange, Expr *EndRange,
  1730. QualType RangeType,
  1731. VarDecl *BeginVar,
  1732. VarDecl *EndVar,
  1733. SourceLocation ColonLoc,
  1734. OverloadCandidateSet *CandidateSet,
  1735. ExprResult *BeginExpr,
  1736. ExprResult *EndExpr,
  1737. Sema::BeginEndFunction *BEF) {
  1738. DeclarationNameInfo BeginNameInfo(
  1739. &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
  1740. DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
  1741. ColonLoc);
  1742. LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
  1743. Sema::LookupMemberName);
  1744. LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
  1745. if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
  1746. // - if _RangeT is a class type, the unqualified-ids begin and end are
  1747. // looked up in the scope of class _RangeT as if by class member access
  1748. // lookup (3.4.5), and if either (or both) finds at least one
  1749. // declaration, begin-expr and end-expr are __range.begin() and
  1750. // __range.end(), respectively;
  1751. SemaRef.LookupQualifiedName(BeginMemberLookup, D);
  1752. SemaRef.LookupQualifiedName(EndMemberLookup, D);
  1753. if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
  1754. SourceLocation RangeLoc = BeginVar->getLocation();
  1755. *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
  1756. SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
  1757. << RangeLoc << BeginRange->getType() << *BEF;
  1758. return Sema::FRS_DiagnosticIssued;
  1759. }
  1760. } else {
  1761. // - otherwise, begin-expr and end-expr are begin(__range) and
  1762. // end(__range), respectively, where begin and end are looked up with
  1763. // argument-dependent lookup (3.4.2). For the purposes of this name
  1764. // lookup, namespace std is an associated namespace.
  1765. }
  1766. *BEF = Sema::BEF_begin;
  1767. Sema::ForRangeStatus RangeStatus =
  1768. SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
  1769. Sema::BEF_begin, BeginNameInfo,
  1770. BeginMemberLookup, CandidateSet,
  1771. BeginRange, BeginExpr);
  1772. if (RangeStatus != Sema::FRS_Success)
  1773. return RangeStatus;
  1774. if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
  1775. diag::err_for_range_iter_deduction_failure)) {
  1776. NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
  1777. return Sema::FRS_DiagnosticIssued;
  1778. }
  1779. *BEF = Sema::BEF_end;
  1780. RangeStatus =
  1781. SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
  1782. Sema::BEF_end, EndNameInfo,
  1783. EndMemberLookup, CandidateSet,
  1784. EndRange, EndExpr);
  1785. if (RangeStatus != Sema::FRS_Success)
  1786. return RangeStatus;
  1787. if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
  1788. diag::err_for_range_iter_deduction_failure)) {
  1789. NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
  1790. return Sema::FRS_DiagnosticIssued;
  1791. }
  1792. return Sema::FRS_Success;
  1793. }
  1794. /// Speculatively attempt to dereference an invalid range expression.
  1795. /// If the attempt fails, this function will return a valid, null StmtResult
  1796. /// and emit no diagnostics.
  1797. static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
  1798. SourceLocation ForLoc,
  1799. Stmt *LoopVarDecl,
  1800. SourceLocation ColonLoc,
  1801. Expr *Range,
  1802. SourceLocation RangeLoc,
  1803. SourceLocation RParenLoc) {
  1804. // Determine whether we can rebuild the for-range statement with a
  1805. // dereferenced range expression.
  1806. ExprResult AdjustedRange;
  1807. {
  1808. Sema::SFINAETrap Trap(SemaRef);
  1809. AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
  1810. if (AdjustedRange.isInvalid())
  1811. return StmtResult();
  1812. StmtResult SR =
  1813. SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
  1814. AdjustedRange.get(), RParenLoc,
  1815. Sema::BFRK_Check);
  1816. if (SR.isInvalid())
  1817. return StmtResult();
  1818. }
  1819. // The attempt to dereference worked well enough that it could produce a valid
  1820. // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
  1821. // case there are any other (non-fatal) problems with it.
  1822. SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
  1823. << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
  1824. return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
  1825. AdjustedRange.get(), RParenLoc,
  1826. Sema::BFRK_Rebuild);
  1827. }
  1828. namespace {
  1829. /// RAII object to automatically invalidate a declaration if an error occurs.
  1830. struct InvalidateOnErrorScope {
  1831. InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
  1832. : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
  1833. ~InvalidateOnErrorScope() {
  1834. if (Enabled && Trap.hasErrorOccurred())
  1835. D->setInvalidDecl();
  1836. }
  1837. DiagnosticErrorTrap Trap;
  1838. Decl *D;
  1839. bool Enabled;
  1840. };
  1841. }
  1842. /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
  1843. StmtResult
  1844. Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
  1845. Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
  1846. Expr *Inc, Stmt *LoopVarDecl,
  1847. SourceLocation RParenLoc, BuildForRangeKind Kind) {
  1848. Scope *S = getCurScope();
  1849. DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
  1850. VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
  1851. QualType RangeVarType = RangeVar->getType();
  1852. DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
  1853. VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
  1854. // If we hit any errors, mark the loop variable as invalid if its type
  1855. // contains 'auto'.
  1856. InvalidateOnErrorScope Invalidate(*this, LoopVar,
  1857. LoopVar->getType()->isUndeducedType());
  1858. StmtResult BeginEndDecl = BeginEnd;
  1859. ExprResult NotEqExpr = Cond, IncrExpr = Inc;
  1860. if (RangeVarType->isDependentType()) {
  1861. // The range is implicitly used as a placeholder when it is dependent.
  1862. RangeVar->markUsed(Context);
  1863. // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
  1864. // them in properly when we instantiate the loop.
  1865. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
  1866. LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
  1867. } else if (!BeginEndDecl.get()) {
  1868. SourceLocation RangeLoc = RangeVar->getLocation();
  1869. const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
  1870. ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
  1871. VK_LValue, ColonLoc);
  1872. if (BeginRangeRef.isInvalid())
  1873. return StmtError();
  1874. ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
  1875. VK_LValue, ColonLoc);
  1876. if (EndRangeRef.isInvalid())
  1877. return StmtError();
  1878. QualType AutoType = Context.getAutoDeductType();
  1879. Expr *Range = RangeVar->getInit();
  1880. if (!Range)
  1881. return StmtError();
  1882. QualType RangeType = Range->getType();
  1883. if (RequireCompleteType(RangeLoc, RangeType,
  1884. diag::err_for_range_incomplete_type))
  1885. return StmtError();
  1886. // Build auto __begin = begin-expr, __end = end-expr.
  1887. VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
  1888. "__begin");
  1889. VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
  1890. "__end");
  1891. // Build begin-expr and end-expr and attach to __begin and __end variables.
  1892. ExprResult BeginExpr, EndExpr;
  1893. if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
  1894. // - if _RangeT is an array type, begin-expr and end-expr are __range and
  1895. // __range + __bound, respectively, where __bound is the array bound. If
  1896. // _RangeT is an array of unknown size or an array of incomplete type,
  1897. // the program is ill-formed;
  1898. // begin-expr is __range.
  1899. BeginExpr = BeginRangeRef;
  1900. if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
  1901. diag::err_for_range_iter_deduction_failure)) {
  1902. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  1903. return StmtError();
  1904. }
  1905. // Find the array bound.
  1906. ExprResult BoundExpr;
  1907. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
  1908. BoundExpr = IntegerLiteral::Create(
  1909. Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
  1910. else if (const VariableArrayType *VAT =
  1911. dyn_cast<VariableArrayType>(UnqAT))
  1912. BoundExpr = VAT->getSizeExpr();
  1913. else {
  1914. // Can't be a DependentSizedArrayType or an IncompleteArrayType since
  1915. // UnqAT is not incomplete and Range is not type-dependent.
  1916. llvm_unreachable("Unexpected array type in for-range");
  1917. }
  1918. // end-expr is __range + __bound.
  1919. EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
  1920. BoundExpr.get());
  1921. if (EndExpr.isInvalid())
  1922. return StmtError();
  1923. if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
  1924. diag::err_for_range_iter_deduction_failure)) {
  1925. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  1926. return StmtError();
  1927. }
  1928. } else {
  1929. OverloadCandidateSet CandidateSet(RangeLoc,
  1930. OverloadCandidateSet::CSK_Normal);
  1931. Sema::BeginEndFunction BEFFailure;
  1932. ForRangeStatus RangeStatus =
  1933. BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
  1934. EndRangeRef.get(), RangeType,
  1935. BeginVar, EndVar, ColonLoc, &CandidateSet,
  1936. &BeginExpr, &EndExpr, &BEFFailure);
  1937. if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
  1938. BEFFailure == BEF_begin) {
  1939. // If the range is being built from an array parameter, emit a
  1940. // a diagnostic that it is being treated as a pointer.
  1941. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
  1942. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  1943. QualType ArrayTy = PVD->getOriginalType();
  1944. QualType PointerTy = PVD->getType();
  1945. if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
  1946. Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
  1947. << RangeLoc << PVD << ArrayTy << PointerTy;
  1948. Diag(PVD->getLocation(), diag::note_declared_at);
  1949. return StmtError();
  1950. }
  1951. }
  1952. }
  1953. // If building the range failed, try dereferencing the range expression
  1954. // unless a diagnostic was issued or the end function is problematic.
  1955. StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
  1956. LoopVarDecl, ColonLoc,
  1957. Range, RangeLoc,
  1958. RParenLoc);
  1959. if (SR.isInvalid() || SR.isUsable())
  1960. return SR;
  1961. }
  1962. // Otherwise, emit diagnostics if we haven't already.
  1963. if (RangeStatus == FRS_NoViableFunction) {
  1964. Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
  1965. Diag(Range->getLocStart(), diag::err_for_range_invalid)
  1966. << RangeLoc << Range->getType() << BEFFailure;
  1967. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
  1968. }
  1969. // Return an error if no fix was discovered.
  1970. if (RangeStatus != FRS_Success)
  1971. return StmtError();
  1972. }
  1973. assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
  1974. "invalid range expression in for loop");
  1975. // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
  1976. QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
  1977. if (!Context.hasSameType(BeginType, EndType)) {
  1978. Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
  1979. << BeginType << EndType;
  1980. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  1981. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  1982. }
  1983. Decl *BeginEndDecls[] = { BeginVar, EndVar };
  1984. // Claim the type doesn't contain auto: we've already done the checking.
  1985. DeclGroupPtrTy BeginEndGroup =
  1986. BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
  1987. /*TypeMayContainAuto=*/ false);
  1988. BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
  1989. const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
  1990. ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  1991. VK_LValue, ColonLoc);
  1992. if (BeginRef.isInvalid())
  1993. return StmtError();
  1994. ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
  1995. VK_LValue, ColonLoc);
  1996. if (EndRef.isInvalid())
  1997. return StmtError();
  1998. // Build and check __begin != __end expression.
  1999. NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
  2000. BeginRef.get(), EndRef.get());
  2001. NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
  2002. NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
  2003. if (NotEqExpr.isInvalid()) {
  2004. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2005. << RangeLoc << 0 << BeginRangeRef.get()->getType();
  2006. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2007. if (!Context.hasSameType(BeginType, EndType))
  2008. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  2009. return StmtError();
  2010. }
  2011. // Build and check ++__begin expression.
  2012. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  2013. VK_LValue, ColonLoc);
  2014. if (BeginRef.isInvalid())
  2015. return StmtError();
  2016. IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
  2017. IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
  2018. if (IncrExpr.isInvalid()) {
  2019. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2020. << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
  2021. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2022. return StmtError();
  2023. }
  2024. // Build and check *__begin expression.
  2025. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  2026. VK_LValue, ColonLoc);
  2027. if (BeginRef.isInvalid())
  2028. return StmtError();
  2029. ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
  2030. if (DerefExpr.isInvalid()) {
  2031. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2032. << RangeLoc << 1 << BeginRangeRef.get()->getType();
  2033. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2034. return StmtError();
  2035. }
  2036. // Attach *__begin as initializer for VD. Don't touch it if we're just
  2037. // trying to determine whether this would be a valid range.
  2038. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
  2039. AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
  2040. /*TypeMayContainAuto=*/true);
  2041. if (LoopVar->isInvalidDecl())
  2042. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2043. }
  2044. }
  2045. // Don't bother to actually allocate the result if we're just trying to
  2046. // determine whether it would be valid.
  2047. if (Kind == BFRK_Check)
  2048. return StmtResult();
  2049. return new (Context) CXXForRangeStmt(
  2050. RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
  2051. IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
  2052. }
  2053. /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
  2054. /// statement.
  2055. StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
  2056. if (!S || !B)
  2057. return StmtError();
  2058. ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
  2059. ForStmt->setBody(B);
  2060. return S;
  2061. }
  2062. // Warn when the loop variable is a const reference that creates a copy.
  2063. // Suggest using the non-reference type for copies. If a copy can be prevented
  2064. // suggest the const reference type that would do so.
  2065. // For instance, given "for (const &Foo : Range)", suggest
  2066. // "for (const Foo : Range)" to denote a copy is made for the loop. If
  2067. // possible, also suggest "for (const &Bar : Range)" if this type prevents
  2068. // the copy altogether.
  2069. static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
  2070. const VarDecl *VD,
  2071. QualType RangeInitType) {
  2072. const Expr *InitExpr = VD->getInit();
  2073. if (!InitExpr)
  2074. return;
  2075. QualType VariableType = VD->getType();
  2076. const MaterializeTemporaryExpr *MTE =
  2077. dyn_cast<MaterializeTemporaryExpr>(InitExpr);
  2078. // No copy made.
  2079. if (!MTE)
  2080. return;
  2081. const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
  2082. // Searching for either UnaryOperator for dereference of a pointer or
  2083. // CXXOperatorCallExpr for handling iterators.
  2084. while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
  2085. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
  2086. E = CCE->getArg(0);
  2087. } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
  2088. const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
  2089. E = ME->getBase();
  2090. } else {
  2091. const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
  2092. E = MTE->GetTemporaryExpr();
  2093. }
  2094. E = E->IgnoreImpCasts();
  2095. }
  2096. bool ReturnsReference = false;
  2097. if (isa<UnaryOperator>(E)) {
  2098. ReturnsReference = true;
  2099. } else {
  2100. const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
  2101. const FunctionDecl *FD = Call->getDirectCallee();
  2102. QualType ReturnType = FD->getReturnType();
  2103. ReturnsReference = ReturnType->isReferenceType();
  2104. }
  2105. if (ReturnsReference) {
  2106. // Loop variable creates a temporary. Suggest either to go with
  2107. // non-reference loop variable to indiciate a copy is made, or
  2108. // the correct time to bind a const reference.
  2109. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
  2110. << VD << VariableType << E->getType();
  2111. QualType NonReferenceType = VariableType.getNonReferenceType();
  2112. NonReferenceType.removeLocalConst();
  2113. QualType NewReferenceType =
  2114. SemaRef.Context.getLValueReferenceType(E->getType().withConst());
  2115. SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
  2116. << NonReferenceType << NewReferenceType << VD->getSourceRange();
  2117. } else {
  2118. // The range always returns a copy, so a temporary is always created.
  2119. // Suggest removing the reference from the loop variable.
  2120. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
  2121. << VD << RangeInitType;
  2122. QualType NonReferenceType = VariableType.getNonReferenceType();
  2123. NonReferenceType.removeLocalConst();
  2124. SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
  2125. << NonReferenceType << VD->getSourceRange();
  2126. }
  2127. }
  2128. // Warns when the loop variable can be changed to a reference type to
  2129. // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
  2130. // "for (const Foo &x : Range)" if this form does not make a copy.
  2131. static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
  2132. const VarDecl *VD) {
  2133. const Expr *InitExpr = VD->getInit();
  2134. if (!InitExpr)
  2135. return;
  2136. QualType VariableType = VD->getType();
  2137. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
  2138. if (!CE->getConstructor()->isCopyConstructor())
  2139. return;
  2140. } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
  2141. if (CE->getCastKind() != CK_LValueToRValue)
  2142. return;
  2143. } else {
  2144. return;
  2145. }
  2146. // TODO: Determine a maximum size that a POD type can be before a diagnostic
  2147. // should be emitted. Also, only ignore POD types with trivial copy
  2148. // constructors.
  2149. if (VariableType.isPODType(SemaRef.Context))
  2150. return;
  2151. // Suggest changing from a const variable to a const reference variable
  2152. // if doing so will prevent a copy.
  2153. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
  2154. << VD << VariableType << InitExpr->getType();
  2155. SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
  2156. << SemaRef.Context.getLValueReferenceType(VariableType)
  2157. << VD->getSourceRange();
  2158. }
  2159. /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
  2160. /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
  2161. /// using "const foo x" to show that a copy is made
  2162. /// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
  2163. /// Suggest either "const bar x" to keep the copying or "const foo& x" to
  2164. /// prevent the copy.
  2165. /// 3) for (const foo x : foos) where x is constructed from a reference foo.
  2166. /// Suggest "const foo &x" to prevent the copy.
  2167. static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
  2168. const CXXForRangeStmt *ForStmt) {
  2169. if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
  2170. ForStmt->getLocStart()) &&
  2171. SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
  2172. ForStmt->getLocStart()) &&
  2173. SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
  2174. ForStmt->getLocStart())) {
  2175. return;
  2176. }
  2177. const VarDecl *VD = ForStmt->getLoopVariable();
  2178. if (!VD)
  2179. return;
  2180. QualType VariableType = VD->getType();
  2181. if (VariableType->isIncompleteType())
  2182. return;
  2183. const Expr *InitExpr = VD->getInit();
  2184. if (!InitExpr)
  2185. return;
  2186. if (VariableType->isReferenceType()) {
  2187. DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
  2188. ForStmt->getRangeInit()->getType());
  2189. } else if (VariableType.isConstQualified()) {
  2190. DiagnoseForRangeConstVariableCopies(SemaRef, VD);
  2191. }
  2192. }
  2193. /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
  2194. /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
  2195. /// body cannot be performed until after the type of the range variable is
  2196. /// determined.
  2197. StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
  2198. if (!S || !B)
  2199. return StmtError();
  2200. if (isa<ObjCForCollectionStmt>(S))
  2201. return FinishObjCForCollectionStmt(S, B);
  2202. CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
  2203. ForStmt->setBody(B);
  2204. DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
  2205. diag::warn_empty_range_based_for_body);
  2206. DiagnoseForRangeVariableCopies(*this, ForStmt);
  2207. return S;
  2208. }
  2209. StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
  2210. SourceLocation LabelLoc,
  2211. LabelDecl *TheDecl) {
  2212. getCurFunction()->setHasBranchIntoScope();
  2213. TheDecl->markUsed(Context);
  2214. return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
  2215. }
  2216. StmtResult
  2217. Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
  2218. Expr *E) {
  2219. // Convert operand to void*
  2220. if (!E->isTypeDependent()) {
  2221. QualType ETy = E->getType();
  2222. QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
  2223. ExprResult ExprRes = E;
  2224. AssignConvertType ConvTy =
  2225. CheckSingleAssignmentConstraints(DestTy, ExprRes);
  2226. if (ExprRes.isInvalid())
  2227. return StmtError();
  2228. E = ExprRes.get();
  2229. if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
  2230. return StmtError();
  2231. }
  2232. ExprResult ExprRes = ActOnFinishFullExpr(E);
  2233. if (ExprRes.isInvalid())
  2234. return StmtError();
  2235. E = ExprRes.get();
  2236. getCurFunction()->setHasIndirectGoto();
  2237. return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
  2238. }
  2239. static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
  2240. const Scope &DestScope) {
  2241. if (!S.CurrentSEHFinally.empty() &&
  2242. DestScope.Contains(*S.CurrentSEHFinally.back())) {
  2243. S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
  2244. }
  2245. }
  2246. StmtResult
  2247. Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
  2248. Scope *S = CurScope->getContinueParent();
  2249. if (!S) {
  2250. // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
  2251. return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
  2252. }
  2253. CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
  2254. return new (Context) ContinueStmt(ContinueLoc);
  2255. }
  2256. StmtResult
  2257. Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
  2258. Scope *S = CurScope->getBreakParent();
  2259. if (!S) {
  2260. // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
  2261. return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
  2262. }
  2263. if (S->isOpenMPLoopScope())
  2264. return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
  2265. << "break");
  2266. CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
  2267. return new (Context) BreakStmt(BreakLoc);
  2268. }
  2269. /// \brief Determine whether the given expression is a candidate for
  2270. /// copy elision in either a return statement or a throw expression.
  2271. ///
  2272. /// \param ReturnType If we're determining the copy elision candidate for
  2273. /// a return statement, this is the return type of the function. If we're
  2274. /// determining the copy elision candidate for a throw expression, this will
  2275. /// be a NULL type.
  2276. ///
  2277. /// \param E The expression being returned from the function or block, or
  2278. /// being thrown.
  2279. ///
  2280. /// \param AllowFunctionParameter Whether we allow function parameters to
  2281. /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
  2282. /// we re-use this logic to determine whether we should try to move as part of
  2283. /// a return or throw (which does allow function parameters).
  2284. ///
  2285. /// \returns The NRVO candidate variable, if the return statement may use the
  2286. /// NRVO, or NULL if there is no such candidate.
  2287. VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
  2288. Expr *E,
  2289. bool AllowFunctionParameter) {
  2290. if (!getLangOpts().CPlusPlus)
  2291. return nullptr;
  2292. // - in a return statement in a function [where] ...
  2293. // ... the expression is the name of a non-volatile automatic object ...
  2294. DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
  2295. if (!DR || DR->refersToEnclosingVariableOrCapture())
  2296. return nullptr;
  2297. VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  2298. if (!VD)
  2299. return nullptr;
  2300. if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
  2301. return VD;
  2302. return nullptr;
  2303. }
  2304. bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
  2305. bool AllowFunctionParameter) {
  2306. QualType VDType = VD->getType();
  2307. // - in a return statement in a function with ...
  2308. // ... a class return type ...
  2309. if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
  2310. if (!ReturnType->isRecordType())
  2311. return false;
  2312. // ... the same cv-unqualified type as the function return type ...
  2313. if (!VDType->isDependentType() &&
  2314. !Context.hasSameUnqualifiedType(ReturnType, VDType))
  2315. return false;
  2316. }
  2317. // ...object (other than a function or catch-clause parameter)...
  2318. if (VD->getKind() != Decl::Var &&
  2319. !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
  2320. return false;
  2321. if (VD->isExceptionVariable()) return false;
  2322. // ...automatic...
  2323. if (!VD->hasLocalStorage()) return false;
  2324. // ...non-volatile...
  2325. if (VD->getType().isVolatileQualified()) return false;
  2326. // __block variables can't be allocated in a way that permits NRVO.
  2327. if (VD->hasAttr<BlocksAttr>()) return false;
  2328. // Variables with higher required alignment than their type's ABI
  2329. // alignment cannot use NRVO.
  2330. if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
  2331. Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
  2332. return false;
  2333. return true;
  2334. }
  2335. /// \brief Perform the initialization of a potentially-movable value, which
  2336. /// is the result of return value.
  2337. ///
  2338. /// This routine implements C++0x [class.copy]p33, which attempts to treat
  2339. /// returned lvalues as rvalues in certain cases (to prefer move construction),
  2340. /// then falls back to treating them as lvalues if that failed.
  2341. ExprResult
  2342. Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
  2343. const VarDecl *NRVOCandidate,
  2344. QualType ResultType,
  2345. Expr *Value,
  2346. bool AllowNRVO) {
  2347. // C++0x [class.copy]p33:
  2348. // When the criteria for elision of a copy operation are met or would
  2349. // be met save for the fact that the source object is a function
  2350. // parameter, and the object to be copied is designated by an lvalue,
  2351. // overload resolution to select the constructor for the copy is first
  2352. // performed as if the object were designated by an rvalue.
  2353. ExprResult Res = ExprError();
  2354. if (AllowNRVO &&
  2355. (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
  2356. ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
  2357. Value->getType(), CK_NoOp, Value, VK_XValue);
  2358. Expr *InitExpr = &AsRvalue;
  2359. InitializationKind Kind
  2360. = InitializationKind::CreateCopy(Value->getLocStart(),
  2361. Value->getLocStart());
  2362. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  2363. // [...] If overload resolution fails, or if the type of the first
  2364. // parameter of the selected constructor is not an rvalue reference
  2365. // to the object's type (possibly cv-qualified), overload resolution
  2366. // is performed again, considering the object as an lvalue.
  2367. if (Seq) {
  2368. for (InitializationSequence::step_iterator Step = Seq.step_begin(),
  2369. StepEnd = Seq.step_end();
  2370. Step != StepEnd; ++Step) {
  2371. if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
  2372. continue;
  2373. CXXConstructorDecl *Constructor
  2374. = cast<CXXConstructorDecl>(Step->Function.Function);
  2375. const RValueReferenceType *RRefType
  2376. = Constructor->getParamDecl(0)->getType()
  2377. ->getAs<RValueReferenceType>();
  2378. // If we don't meet the criteria, break out now.
  2379. if (!RRefType ||
  2380. !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
  2381. Context.getTypeDeclType(Constructor->getParent())))
  2382. break;
  2383. // Promote "AsRvalue" to the heap, since we now need this
  2384. // expression node to persist.
  2385. Value = ImplicitCastExpr::Create(Context, Value->getType(),
  2386. CK_NoOp, Value, nullptr, VK_XValue);
  2387. // Complete type-checking the initialization of the return type
  2388. // using the constructor we found.
  2389. Res = Seq.Perform(*this, Entity, Kind, Value);
  2390. }
  2391. }
  2392. }
  2393. // Either we didn't meet the criteria for treating an lvalue as an rvalue,
  2394. // above, or overload resolution failed. Either way, we need to try
  2395. // (again) now with the return value expression as written.
  2396. if (Res.isInvalid())
  2397. Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
  2398. return Res;
  2399. }
  2400. /// \brief Determine whether the declared return type of the specified function
  2401. /// contains 'auto'.
  2402. static bool hasDeducedReturnType(FunctionDecl *FD) {
  2403. const FunctionProtoType *FPT =
  2404. FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
  2405. return FPT->getReturnType()->isUndeducedType();
  2406. }
  2407. /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
  2408. /// for capturing scopes.
  2409. ///
  2410. StmtResult
  2411. Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
  2412. // If this is the first return we've seen, infer the return type.
  2413. // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
  2414. CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
  2415. QualType FnRetType = CurCap->ReturnType;
  2416. LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
  2417. if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
  2418. // In C++1y, the return type may involve 'auto'.
  2419. // FIXME: Blocks might have a return type of 'auto' explicitly specified.
  2420. FunctionDecl *FD = CurLambda->CallOperator;
  2421. if (CurCap->ReturnType.isNull())
  2422. CurCap->ReturnType = FD->getReturnType();
  2423. AutoType *AT = CurCap->ReturnType->getContainedAutoType();
  2424. assert(AT && "lost auto type from lambda return type");
  2425. if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
  2426. FD->setInvalidDecl();
  2427. return StmtError();
  2428. }
  2429. CurCap->ReturnType = FnRetType = FD->getReturnType();
  2430. } else if (CurCap->HasImplicitReturnType) {
  2431. // For blocks/lambdas with implicit return types, we check each return
  2432. // statement individually, and deduce the common return type when the block
  2433. // or lambda is completed.
  2434. // FIXME: Fold this into the 'auto' codepath above.
  2435. if (RetValExp && !isa<InitListExpr>(RetValExp)) {
  2436. ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
  2437. if (Result.isInvalid())
  2438. return StmtError();
  2439. RetValExp = Result.get();
  2440. // DR1048: even prior to C++14, we should use the 'auto' deduction rules
  2441. // when deducing a return type for a lambda-expression (or by extension
  2442. // for a block). These rules differ from the stated C++11 rules only in
  2443. // that they remove top-level cv-qualifiers.
  2444. if (!CurContext->isDependentContext())
  2445. FnRetType = RetValExp->getType().getUnqualifiedType();
  2446. else
  2447. FnRetType = CurCap->ReturnType = Context.DependentTy;
  2448. } else {
  2449. if (RetValExp) {
  2450. // C++11 [expr.lambda.prim]p4 bans inferring the result from an
  2451. // initializer list, because it is not an expression (even
  2452. // though we represent it as one). We still deduce 'void'.
  2453. Diag(ReturnLoc, diag::err_lambda_return_init_list)
  2454. << RetValExp->getSourceRange();
  2455. }
  2456. FnRetType = Context.VoidTy;
  2457. }
  2458. // Although we'll properly infer the type of the block once it's completed,
  2459. // make sure we provide a return type now for better error recovery.
  2460. if (CurCap->ReturnType.isNull())
  2461. CurCap->ReturnType = FnRetType;
  2462. }
  2463. assert(!FnRetType.isNull());
  2464. if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
  2465. if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
  2466. Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
  2467. return StmtError();
  2468. }
  2469. } else if (CapturedRegionScopeInfo *CurRegion =
  2470. dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
  2471. Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
  2472. return StmtError();
  2473. } else {
  2474. assert(CurLambda && "unknown kind of captured scope");
  2475. if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
  2476. ->getNoReturnAttr()) {
  2477. Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
  2478. return StmtError();
  2479. }
  2480. }
  2481. // Otherwise, verify that this result type matches the previous one. We are
  2482. // pickier with blocks than for normal functions because we don't have GCC
  2483. // compatibility to worry about here.
  2484. const VarDecl *NRVOCandidate = nullptr;
  2485. if (FnRetType->isDependentType()) {
  2486. // Delay processing for now. TODO: there are lots of dependent
  2487. // types we can conclusively prove aren't void.
  2488. } else if (FnRetType->isVoidType()) {
  2489. if (RetValExp && !isa<InitListExpr>(RetValExp) &&
  2490. !(getLangOpts().CPlusPlus &&
  2491. (RetValExp->isTypeDependent() ||
  2492. RetValExp->getType()->isVoidType()))) {
  2493. if (!getLangOpts().CPlusPlus &&
  2494. RetValExp->getType()->isVoidType())
  2495. Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
  2496. else {
  2497. Diag(ReturnLoc, diag::err_return_block_has_expr);
  2498. RetValExp = nullptr;
  2499. }
  2500. }
  2501. } else if (!RetValExp) {
  2502. return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
  2503. } else if (!RetValExp->isTypeDependent()) {
  2504. // we have a non-void block with an expression, continue checking
  2505. // C99 6.8.6.4p3(136): The return statement is not an assignment. The
  2506. // overlap restriction of subclause 6.5.16.1 does not apply to the case of
  2507. // function return.
  2508. // In C++ the return statement is handled via a copy initialization.
  2509. // the C version of which boils down to CheckSingleAssignmentConstraints.
  2510. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
  2511. InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
  2512. FnRetType,
  2513. NRVOCandidate != nullptr);
  2514. ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
  2515. FnRetType, RetValExp);
  2516. if (Res.isInvalid()) {
  2517. // FIXME: Cleanup temporaries here, anyway?
  2518. return StmtError();
  2519. }
  2520. RetValExp = Res.get();
  2521. CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
  2522. } else {
  2523. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
  2524. }
  2525. if (RetValExp) {
  2526. ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
  2527. if (ER.isInvalid())
  2528. return StmtError();
  2529. RetValExp = ER.get();
  2530. }
  2531. ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
  2532. NRVOCandidate);
  2533. // If we need to check for the named return value optimization,
  2534. // or if we need to infer the return type,
  2535. // save the return statement in our scope for later processing.
  2536. if (CurCap->HasImplicitReturnType || NRVOCandidate)
  2537. FunctionScopes.back()->Returns.push_back(Result);
  2538. return Result;
  2539. }
  2540. namespace {
  2541. /// \brief Marks all typedefs in all local classes in a type referenced.
  2542. ///
  2543. /// In a function like
  2544. /// auto f() {
  2545. /// struct S { typedef int a; };
  2546. /// return S();
  2547. /// }
  2548. ///
  2549. /// the local type escapes and could be referenced in some TUs but not in
  2550. /// others. Pretend that all local typedefs are always referenced, to not warn
  2551. /// on this. This isn't necessary if f has internal linkage, or the typedef
  2552. /// is private.
  2553. class LocalTypedefNameReferencer
  2554. : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
  2555. public:
  2556. LocalTypedefNameReferencer(Sema &S) : S(S) {}
  2557. bool VisitRecordType(const RecordType *RT);
  2558. private:
  2559. Sema &S;
  2560. };
  2561. bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
  2562. auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
  2563. if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
  2564. R->isDependentType())
  2565. return true;
  2566. for (auto *TmpD : R->decls())
  2567. if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  2568. if (T->getAccess() != AS_private || R->hasFriends())
  2569. S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
  2570. return true;
  2571. }
  2572. }
  2573. TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
  2574. TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
  2575. while (auto ATL = TL.getAs<AttributedTypeLoc>())
  2576. TL = ATL.getModifiedLoc().IgnoreParens();
  2577. return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
  2578. }
  2579. /// Deduce the return type for a function from a returned expression, per
  2580. /// C++1y [dcl.spec.auto]p6.
  2581. bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
  2582. SourceLocation ReturnLoc,
  2583. Expr *&RetExpr,
  2584. AutoType *AT) {
  2585. TypeLoc OrigResultType = getReturnTypeLoc(FD);
  2586. QualType Deduced;
  2587. if (RetExpr && isa<InitListExpr>(RetExpr)) {
  2588. // If the deduction is for a return statement and the initializer is
  2589. // a braced-init-list, the program is ill-formed.
  2590. Diag(RetExpr->getExprLoc(),
  2591. getCurLambda() ? diag::err_lambda_return_init_list
  2592. : diag::err_auto_fn_return_init_list)
  2593. << RetExpr->getSourceRange();
  2594. return true;
  2595. }
  2596. if (FD->isDependentContext()) {
  2597. // C++1y [dcl.spec.auto]p12:
  2598. // Return type deduction [...] occurs when the definition is
  2599. // instantiated even if the function body contains a return
  2600. // statement with a non-type-dependent operand.
  2601. assert(AT->isDeduced() && "should have deduced to dependent type");
  2602. return false;
  2603. } else if (RetExpr) {
  2604. // If the deduction is for a return statement and the initializer is
  2605. // a braced-init-list, the program is ill-formed.
  2606. if (isa<InitListExpr>(RetExpr)) {
  2607. Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
  2608. return true;
  2609. }
  2610. // Otherwise, [...] deduce a value for U using the rules of template
  2611. // argument deduction.
  2612. DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
  2613. if (DAR == DAR_Failed && !FD->isInvalidDecl())
  2614. Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
  2615. << OrigResultType.getType() << RetExpr->getType();
  2616. if (DAR != DAR_Succeeded)
  2617. return true;
  2618. // If a local type is part of the returned type, mark its fields as
  2619. // referenced.
  2620. LocalTypedefNameReferencer Referencer(*this);
  2621. Referencer.TraverseType(RetExpr->getType());
  2622. } else {
  2623. // In the case of a return with no operand, the initializer is considered
  2624. // to be void().
  2625. //
  2626. // Deduction here can only succeed if the return type is exactly 'cv auto'
  2627. // or 'decltype(auto)', so just check for that case directly.
  2628. if (!OrigResultType.getType()->getAs<AutoType>()) {
  2629. Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
  2630. << OrigResultType.getType();
  2631. return true;
  2632. }
  2633. // We always deduce U = void in this case.
  2634. Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
  2635. if (Deduced.isNull())
  2636. return true;
  2637. }
  2638. // If a function with a declared return type that contains a placeholder type
  2639. // has multiple return statements, the return type is deduced for each return
  2640. // statement. [...] if the type deduced is not the same in each deduction,
  2641. // the program is ill-formed.
  2642. if (AT->isDeduced() && !FD->isInvalidDecl()) {
  2643. AutoType *NewAT = Deduced->getContainedAutoType();
  2644. if (!FD->isDependentContext() &&
  2645. !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
  2646. const LambdaScopeInfo *LambdaSI = getCurLambda();
  2647. if (LambdaSI && LambdaSI->HasImplicitReturnType) {
  2648. Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
  2649. << NewAT->getDeducedType() << AT->getDeducedType()
  2650. << true /*IsLambda*/;
  2651. } else {
  2652. Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
  2653. << (AT->isDecltypeAuto() ? 1 : 0)
  2654. << NewAT->getDeducedType() << AT->getDeducedType();
  2655. }
  2656. return true;
  2657. }
  2658. } else if (!FD->isInvalidDecl()) {
  2659. // Update all declarations of the function to have the deduced return type.
  2660. Context.adjustDeducedFunctionResultType(FD, Deduced);
  2661. }
  2662. return false;
  2663. }
  2664. StmtResult
  2665. Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  2666. Scope *CurScope) {
  2667. StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
  2668. if (R.isInvalid()) {
  2669. return R;
  2670. }
  2671. if (VarDecl *VD =
  2672. const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
  2673. CurScope->addNRVOCandidate(VD);
  2674. } else {
  2675. CurScope->setNoNRVO();
  2676. }
  2677. CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
  2678. return R;
  2679. }
  2680. StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
  2681. // Check for unexpanded parameter packs.
  2682. if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
  2683. return StmtError();
  2684. if (isa<CapturingScopeInfo>(getCurFunction()))
  2685. return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
  2686. QualType FnRetType;
  2687. QualType RelatedRetType;
  2688. const AttrVec *Attrs = nullptr;
  2689. bool isObjCMethod = false;
  2690. if (const FunctionDecl *FD = getCurFunctionDecl()) {
  2691. FnRetType = FD->getReturnType();
  2692. if (FD->hasAttrs())
  2693. Attrs = &FD->getAttrs();
  2694. if (FD->isNoReturn())
  2695. Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
  2696. << FD->getDeclName();
  2697. } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
  2698. FnRetType = MD->getReturnType();
  2699. isObjCMethod = true;
  2700. if (MD->hasAttrs())
  2701. Attrs = &MD->getAttrs();
  2702. if (MD->hasRelatedResultType() && MD->getClassInterface()) {
  2703. // In the implementation of a method with a related return type, the
  2704. // type used to type-check the validity of return statements within the
  2705. // method body is a pointer to the type of the class being implemented.
  2706. RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
  2707. RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
  2708. }
  2709. } else // If we don't have a function/method context, bail.
  2710. return StmtError();
  2711. // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
  2712. // deduction.
  2713. if (getLangOpts().CPlusPlus14) {
  2714. if (AutoType *AT = FnRetType->getContainedAutoType()) {
  2715. FunctionDecl *FD = cast<FunctionDecl>(CurContext);
  2716. if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
  2717. FD->setInvalidDecl();
  2718. return StmtError();
  2719. } else {
  2720. FnRetType = FD->getReturnType();
  2721. }
  2722. }
  2723. }
  2724. bool HasDependentReturnType = FnRetType->isDependentType();
  2725. ReturnStmt *Result = nullptr;
  2726. if (FnRetType->isVoidType()) {
  2727. if (RetValExp) {
  2728. if (isa<InitListExpr>(RetValExp)) {
  2729. // We simply never allow init lists as the return value of void
  2730. // functions. This is compatible because this was never allowed before,
  2731. // so there's no legacy code to deal with.
  2732. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  2733. int FunctionKind = 0;
  2734. if (isa<ObjCMethodDecl>(CurDecl))
  2735. FunctionKind = 1;
  2736. else if (isa<CXXConstructorDecl>(CurDecl))
  2737. FunctionKind = 2;
  2738. else if (isa<CXXDestructorDecl>(CurDecl))
  2739. FunctionKind = 3;
  2740. Diag(ReturnLoc, diag::err_return_init_list)
  2741. << CurDecl->getDeclName() << FunctionKind
  2742. << RetValExp->getSourceRange();
  2743. // Drop the expression.
  2744. RetValExp = nullptr;
  2745. } else if (!RetValExp->isTypeDependent()) {
  2746. // C99 6.8.6.4p1 (ext_ since GCC warns)
  2747. unsigned D = diag::ext_return_has_expr;
  2748. if (RetValExp->getType()->isVoidType()) {
  2749. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  2750. if (isa<CXXConstructorDecl>(CurDecl) ||
  2751. isa<CXXDestructorDecl>(CurDecl))
  2752. D = diag::err_ctor_dtor_returns_void;
  2753. else
  2754. D = diag::ext_return_has_void_expr;
  2755. }
  2756. else {
  2757. ExprResult Result = RetValExp;
  2758. Result = IgnoredValueConversions(Result.get());
  2759. if (Result.isInvalid())
  2760. return StmtError();
  2761. RetValExp = Result.get();
  2762. RetValExp = ImpCastExprToType(RetValExp,
  2763. Context.VoidTy, CK_ToVoid).get();
  2764. }
  2765. // return of void in constructor/destructor is illegal in C++.
  2766. if (D == diag::err_ctor_dtor_returns_void) {
  2767. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  2768. Diag(ReturnLoc, D)
  2769. << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
  2770. << RetValExp->getSourceRange();
  2771. }
  2772. // return (some void expression); is legal in C++.
  2773. else if (D != diag::ext_return_has_void_expr ||
  2774. !getLangOpts().CPlusPlus) {
  2775. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  2776. int FunctionKind = 0;
  2777. if (isa<ObjCMethodDecl>(CurDecl))
  2778. FunctionKind = 1;
  2779. else if (isa<CXXConstructorDecl>(CurDecl))
  2780. FunctionKind = 2;
  2781. else if (isa<CXXDestructorDecl>(CurDecl))
  2782. FunctionKind = 3;
  2783. Diag(ReturnLoc, D)
  2784. << CurDecl->getDeclName() << FunctionKind
  2785. << RetValExp->getSourceRange();
  2786. }
  2787. }
  2788. if (RetValExp) {
  2789. ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
  2790. if (ER.isInvalid())
  2791. return StmtError();
  2792. RetValExp = ER.get();
  2793. }
  2794. }
  2795. Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
  2796. } else if (!RetValExp && !HasDependentReturnType) {
  2797. FunctionDecl *FD = getCurFunctionDecl();
  2798. unsigned DiagID;
  2799. if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
  2800. // C++11 [stmt.return]p2
  2801. DiagID = diag::err_constexpr_return_missing_expr;
  2802. FD->setInvalidDecl();
  2803. } else if (getLangOpts().C99) {
  2804. // C99 6.8.6.4p1 (ext_ since GCC warns)
  2805. DiagID = diag::ext_return_missing_expr;
  2806. } else {
  2807. // C90 6.6.6.4p4
  2808. DiagID = diag::warn_return_missing_expr;
  2809. }
  2810. if (FD)
  2811. Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
  2812. else
  2813. Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
  2814. Result = new (Context) ReturnStmt(ReturnLoc);
  2815. } else {
  2816. assert(RetValExp || HasDependentReturnType);
  2817. const VarDecl *NRVOCandidate = nullptr;
  2818. QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
  2819. // C99 6.8.6.4p3(136): The return statement is not an assignment. The
  2820. // overlap restriction of subclause 6.5.16.1 does not apply to the case of
  2821. // function return.
  2822. // In C++ the return statement is handled via a copy initialization,
  2823. // the C version of which boils down to CheckSingleAssignmentConstraints.
  2824. if (RetValExp)
  2825. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
  2826. if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
  2827. // we have a non-void function with an expression, continue checking
  2828. InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
  2829. RetType,
  2830. NRVOCandidate != nullptr);
  2831. ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
  2832. RetType, RetValExp);
  2833. if (Res.isInvalid()) {
  2834. // FIXME: Clean up temporaries here anyway?
  2835. return StmtError();
  2836. }
  2837. RetValExp = Res.getAs<Expr>();
  2838. // If we have a related result type, we need to implicitly
  2839. // convert back to the formal result type. We can't pretend to
  2840. // initialize the result again --- we might end double-retaining
  2841. // --- so instead we initialize a notional temporary.
  2842. if (!RelatedRetType.isNull()) {
  2843. Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
  2844. FnRetType);
  2845. Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
  2846. if (Res.isInvalid()) {
  2847. // FIXME: Clean up temporaries here anyway?
  2848. return StmtError();
  2849. }
  2850. RetValExp = Res.getAs<Expr>();
  2851. }
  2852. CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
  2853. getCurFunctionDecl());
  2854. }
  2855. if (RetValExp) {
  2856. ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
  2857. if (ER.isInvalid())
  2858. return StmtError();
  2859. RetValExp = ER.get();
  2860. }
  2861. Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
  2862. }
  2863. // If we need to check for the named return value optimization, save the
  2864. // return statement in our scope for later processing.
  2865. if (Result->getNRVOCandidate())
  2866. FunctionScopes.back()->Returns.push_back(Result);
  2867. return Result;
  2868. }
  2869. StmtResult
  2870. Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
  2871. SourceLocation RParen, Decl *Parm,
  2872. Stmt *Body) {
  2873. VarDecl *Var = cast_or_null<VarDecl>(Parm);
  2874. if (Var && Var->isInvalidDecl())
  2875. return StmtError();
  2876. return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
  2877. }
  2878. StmtResult
  2879. Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
  2880. return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
  2881. }
  2882. StmtResult
  2883. Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
  2884. MultiStmtArg CatchStmts, Stmt *Finally) {
  2885. if (!getLangOpts().ObjCExceptions)
  2886. Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
  2887. getCurFunction()->setHasBranchProtectedScope();
  2888. unsigned NumCatchStmts = CatchStmts.size();
  2889. return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
  2890. NumCatchStmts, Finally);
  2891. }
  2892. StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
  2893. if (Throw) {
  2894. ExprResult Result = DefaultLvalueConversion(Throw);
  2895. if (Result.isInvalid())
  2896. return StmtError();
  2897. Result = ActOnFinishFullExpr(Result.get());
  2898. if (Result.isInvalid())
  2899. return StmtError();
  2900. Throw = Result.get();
  2901. QualType ThrowType = Throw->getType();
  2902. // Make sure the expression type is an ObjC pointer or "void *".
  2903. if (!ThrowType->isDependentType() &&
  2904. !ThrowType->isObjCObjectPointerType()) {
  2905. const PointerType *PT = ThrowType->getAs<PointerType>();
  2906. if (!PT || !PT->getPointeeType()->isVoidType())
  2907. return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
  2908. << Throw->getType() << Throw->getSourceRange());
  2909. }
  2910. }
  2911. return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
  2912. }
  2913. StmtResult
  2914. Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
  2915. Scope *CurScope) {
  2916. if (!getLangOpts().ObjCExceptions)
  2917. Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
  2918. if (!Throw) {
  2919. // @throw without an expression designates a rethrow (which must occur
  2920. // in the context of an @catch clause).
  2921. Scope *AtCatchParent = CurScope;
  2922. while (AtCatchParent && !AtCatchParent->isAtCatchScope())
  2923. AtCatchParent = AtCatchParent->getParent();
  2924. if (!AtCatchParent)
  2925. return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
  2926. }
  2927. return BuildObjCAtThrowStmt(AtLoc, Throw);
  2928. }
  2929. ExprResult
  2930. Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
  2931. ExprResult result = DefaultLvalueConversion(operand);
  2932. if (result.isInvalid())
  2933. return ExprError();
  2934. operand = result.get();
  2935. // Make sure the expression type is an ObjC pointer or "void *".
  2936. QualType type = operand->getType();
  2937. if (!type->isDependentType() &&
  2938. !type->isObjCObjectPointerType()) {
  2939. const PointerType *pointerType = type->getAs<PointerType>();
  2940. if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
  2941. if (getLangOpts().CPlusPlus) {
  2942. if (RequireCompleteType(atLoc, type,
  2943. diag::err_incomplete_receiver_type))
  2944. return Diag(atLoc, diag::error_objc_synchronized_expects_object)
  2945. << type << operand->getSourceRange();
  2946. ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
  2947. if (!result.isUsable())
  2948. return Diag(atLoc, diag::error_objc_synchronized_expects_object)
  2949. << type << operand->getSourceRange();
  2950. operand = result.get();
  2951. } else {
  2952. return Diag(atLoc, diag::error_objc_synchronized_expects_object)
  2953. << type << operand->getSourceRange();
  2954. }
  2955. }
  2956. }
  2957. // The operand to @synchronized is a full-expression.
  2958. return ActOnFinishFullExpr(operand);
  2959. }
  2960. StmtResult
  2961. Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
  2962. Stmt *SyncBody) {
  2963. // We can't jump into or indirect-jump out of a @synchronized block.
  2964. getCurFunction()->setHasBranchProtectedScope();
  2965. return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
  2966. }
  2967. /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
  2968. /// and creates a proper catch handler from them.
  2969. StmtResult
  2970. Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
  2971. Stmt *HandlerBlock) {
  2972. // There's nothing to test that ActOnExceptionDecl didn't already test.
  2973. return new (Context)
  2974. CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
  2975. }
  2976. StmtResult
  2977. Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
  2978. getCurFunction()->setHasBranchProtectedScope();
  2979. return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
  2980. }
  2981. namespace {
  2982. class CatchHandlerType {
  2983. QualType QT;
  2984. unsigned IsPointer : 1;
  2985. // This is a special constructor to be used only with DenseMapInfo's
  2986. // getEmptyKey() and getTombstoneKey() functions.
  2987. friend struct llvm::DenseMapInfo<CatchHandlerType>;
  2988. enum Unique { ForDenseMap };
  2989. CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
  2990. public:
  2991. /// Used when creating a CatchHandlerType from a handler type; will determine
  2992. /// whether the type is a pointer or reference and will strip off the top
  2993. /// level pointer and cv-qualifiers.
  2994. CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
  2995. if (QT->isPointerType())
  2996. IsPointer = true;
  2997. if (IsPointer || QT->isReferenceType())
  2998. QT = QT->getPointeeType();
  2999. QT = QT.getUnqualifiedType();
  3000. }
  3001. /// Used when creating a CatchHandlerType from a base class type; pretends the
  3002. /// type passed in had the pointer qualifier, does not need to get an
  3003. /// unqualified type.
  3004. CatchHandlerType(QualType QT, bool IsPointer)
  3005. : QT(QT), IsPointer(IsPointer) {}
  3006. QualType underlying() const { return QT; }
  3007. bool isPointer() const { return IsPointer; }
  3008. friend bool operator==(const CatchHandlerType &LHS,
  3009. const CatchHandlerType &RHS) {
  3010. // If the pointer qualification does not match, we can return early.
  3011. if (LHS.IsPointer != RHS.IsPointer)
  3012. return false;
  3013. // Otherwise, check the underlying type without cv-qualifiers.
  3014. return LHS.QT == RHS.QT;
  3015. }
  3016. };
  3017. } // namespace
  3018. namespace llvm {
  3019. template <> struct DenseMapInfo<CatchHandlerType> {
  3020. static CatchHandlerType getEmptyKey() {
  3021. return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
  3022. CatchHandlerType::ForDenseMap);
  3023. }
  3024. static CatchHandlerType getTombstoneKey() {
  3025. return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
  3026. CatchHandlerType::ForDenseMap);
  3027. }
  3028. static unsigned getHashValue(const CatchHandlerType &Base) {
  3029. return DenseMapInfo<QualType>::getHashValue(Base.underlying());
  3030. }
  3031. static bool isEqual(const CatchHandlerType &LHS,
  3032. const CatchHandlerType &RHS) {
  3033. return LHS == RHS;
  3034. }
  3035. };
  3036. // It's OK to treat CatchHandlerType as a POD type.
  3037. template <> struct isPodLike<CatchHandlerType> {
  3038. static const bool value = true;
  3039. };
  3040. }
  3041. namespace {
  3042. class CatchTypePublicBases {
  3043. ASTContext &Ctx;
  3044. const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
  3045. const bool CheckAgainstPointer;
  3046. CXXCatchStmt *FoundHandler;
  3047. CanQualType FoundHandlerType;
  3048. public:
  3049. CatchTypePublicBases(
  3050. ASTContext &Ctx,
  3051. const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
  3052. : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
  3053. FoundHandler(nullptr) {}
  3054. CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
  3055. CanQualType getFoundHandlerType() const { return FoundHandlerType; }
  3056. static bool FindPublicBasesOfType(const CXXBaseSpecifier *S, CXXBasePath &,
  3057. void *User) {
  3058. auto &PBOT = *reinterpret_cast<CatchTypePublicBases *>(User);
  3059. if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
  3060. CatchHandlerType Check(S->getType(), PBOT.CheckAgainstPointer);
  3061. auto M = PBOT.TypesToCheck;
  3062. auto I = M.find(Check);
  3063. if (I != M.end()) {
  3064. PBOT.FoundHandler = I->second;
  3065. PBOT.FoundHandlerType = PBOT.Ctx.getCanonicalType(S->getType());
  3066. return true;
  3067. }
  3068. }
  3069. return false;
  3070. }
  3071. };
  3072. }
  3073. /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
  3074. /// handlers and creates a try statement from them.
  3075. StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
  3076. ArrayRef<Stmt *> Handlers) {
  3077. // Don't report an error if 'try' is used in system headers.
  3078. if (!getLangOpts().CXXExceptions &&
  3079. !getSourceManager().isInSystemHeader(TryLoc))
  3080. Diag(TryLoc, diag::err_exceptions_disabled) << "try";
  3081. if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
  3082. Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
  3083. sema::FunctionScopeInfo *FSI = getCurFunction();
  3084. // C++ try is incompatible with SEH __try.
  3085. if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
  3086. Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
  3087. Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
  3088. }
  3089. const unsigned NumHandlers = Handlers.size();
  3090. assert(!Handlers.empty() &&
  3091. "The parser shouldn't call this if there are no handlers.");
  3092. llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
  3093. for (unsigned i = 0; i < NumHandlers; ++i) {
  3094. CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
  3095. // Diagnose when the handler is a catch-all handler, but it isn't the last
  3096. // handler for the try block. [except.handle]p5. Also, skip exception
  3097. // declarations that are invalid, since we can't usefully report on them.
  3098. if (!H->getExceptionDecl()) {
  3099. if (i < NumHandlers - 1)
  3100. return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
  3101. continue;
  3102. } else if (H->getExceptionDecl()->isInvalidDecl())
  3103. continue;
  3104. // Walk the type hierarchy to diagnose when this type has already been
  3105. // handled (duplication), or cannot be handled (derivation inversion). We
  3106. // ignore top-level cv-qualifiers, per [except.handle]p3
  3107. CatchHandlerType HandlerCHT =
  3108. (QualType)Context.getCanonicalType(H->getCaughtType());
  3109. // We can ignore whether the type is a reference or a pointer; we need the
  3110. // underlying declaration type in order to get at the underlying record
  3111. // decl, if there is one.
  3112. QualType Underlying = HandlerCHT.underlying();
  3113. if (auto *RD = Underlying->getAsCXXRecordDecl()) {
  3114. if (!RD->hasDefinition())
  3115. continue;
  3116. // Check that none of the public, unambiguous base classes are in the
  3117. // map ([except.handle]p1). Give the base classes the same pointer
  3118. // qualification as the original type we are basing off of. This allows
  3119. // comparison against the handler type using the same top-level pointer
  3120. // as the original type.
  3121. CXXBasePaths Paths;
  3122. Paths.setOrigin(RD);
  3123. CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
  3124. if (RD->lookupInBases(CatchTypePublicBases::FindPublicBasesOfType, &CTPB,
  3125. Paths)) {
  3126. const CXXCatchStmt *Problem = CTPB.getFoundHandler();
  3127. if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
  3128. Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
  3129. diag::warn_exception_caught_by_earlier_handler)
  3130. << H->getCaughtType();
  3131. Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
  3132. diag::note_previous_exception_handler)
  3133. << Problem->getCaughtType();
  3134. }
  3135. }
  3136. }
  3137. // Add the type the list of ones we have handled; diagnose if we've already
  3138. // handled it.
  3139. auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
  3140. if (!R.second) {
  3141. const CXXCatchStmt *Problem = R.first->second;
  3142. Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
  3143. diag::warn_exception_caught_by_earlier_handler)
  3144. << H->getCaughtType();
  3145. Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
  3146. diag::note_previous_exception_handler)
  3147. << Problem->getCaughtType();
  3148. }
  3149. }
  3150. FSI->setHasCXXTry(TryLoc);
  3151. return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
  3152. }
  3153. StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
  3154. Stmt *TryBlock, Stmt *Handler) {
  3155. assert(TryBlock && Handler);
  3156. sema::FunctionScopeInfo *FSI = getCurFunction();
  3157. // SEH __try is incompatible with C++ try. Borland appears to support this,
  3158. // however.
  3159. if (!getLangOpts().Borland) {
  3160. if (FSI->FirstCXXTryLoc.isValid()) {
  3161. Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
  3162. Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
  3163. }
  3164. }
  3165. FSI->setHasSEHTry(TryLoc);
  3166. // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
  3167. // track if they use SEH.
  3168. DeclContext *DC = CurContext;
  3169. while (DC && !DC->isFunctionOrMethod())
  3170. DC = DC->getParent();
  3171. FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
  3172. if (FD)
  3173. FD->setUsesSEHTry(true);
  3174. else
  3175. Diag(TryLoc, diag::err_seh_try_outside_functions);
  3176. // Reject __try on unsupported targets.
  3177. if (!Context.getTargetInfo().isSEHTrySupported())
  3178. Diag(TryLoc, diag::err_seh_try_unsupported);
  3179. return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
  3180. }
  3181. StmtResult
  3182. Sema::ActOnSEHExceptBlock(SourceLocation Loc,
  3183. Expr *FilterExpr,
  3184. Stmt *Block) {
  3185. assert(FilterExpr && Block);
  3186. if(!FilterExpr->getType()->isIntegerType()) {
  3187. return StmtError(Diag(FilterExpr->getExprLoc(),
  3188. diag::err_filter_expression_integral)
  3189. << FilterExpr->getType());
  3190. }
  3191. return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
  3192. }
  3193. void Sema::ActOnStartSEHFinallyBlock() {
  3194. CurrentSEHFinally.push_back(CurScope);
  3195. }
  3196. void Sema::ActOnAbortSEHFinallyBlock() {
  3197. CurrentSEHFinally.pop_back();
  3198. }
  3199. StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
  3200. assert(Block);
  3201. CurrentSEHFinally.pop_back();
  3202. return SEHFinallyStmt::Create(Context, Loc, Block);
  3203. }
  3204. StmtResult
  3205. Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
  3206. Scope *SEHTryParent = CurScope;
  3207. while (SEHTryParent && !SEHTryParent->isSEHTryScope())
  3208. SEHTryParent = SEHTryParent->getParent();
  3209. if (!SEHTryParent)
  3210. return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
  3211. CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
  3212. return new (Context) SEHLeaveStmt(Loc);
  3213. }
  3214. StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
  3215. bool IsIfExists,
  3216. NestedNameSpecifierLoc QualifierLoc,
  3217. DeclarationNameInfo NameInfo,
  3218. Stmt *Nested)
  3219. {
  3220. return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
  3221. QualifierLoc, NameInfo,
  3222. cast<CompoundStmt>(Nested));
  3223. }
  3224. StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
  3225. bool IsIfExists,
  3226. CXXScopeSpec &SS,
  3227. UnqualifiedId &Name,
  3228. Stmt *Nested) {
  3229. return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
  3230. SS.getWithLocInContext(Context),
  3231. GetNameFromUnqualifiedId(Name),
  3232. Nested);
  3233. }
  3234. RecordDecl*
  3235. Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
  3236. unsigned NumParams) {
  3237. DeclContext *DC = CurContext;
  3238. while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
  3239. DC = DC->getParent();
  3240. RecordDecl *RD = nullptr;
  3241. if (getLangOpts().CPlusPlus)
  3242. RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
  3243. /*Id=*/nullptr);
  3244. else
  3245. RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
  3246. RD->setCapturedRecord();
  3247. DC->addDecl(RD);
  3248. RD->setImplicit();
  3249. RD->startDefinition();
  3250. assert(NumParams > 0 && "CapturedStmt requires context parameter");
  3251. CD = CapturedDecl::Create(Context, CurContext, NumParams);
  3252. DC->addDecl(CD);
  3253. return RD;
  3254. }
  3255. static void buildCapturedStmtCaptureList(
  3256. SmallVectorImpl<CapturedStmt::Capture> &Captures,
  3257. SmallVectorImpl<Expr *> &CaptureInits,
  3258. ArrayRef<CapturingScopeInfo::Capture> Candidates) {
  3259. typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
  3260. for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
  3261. if (Cap->isThisCapture()) {
  3262. Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
  3263. CapturedStmt::VCK_This));
  3264. CaptureInits.push_back(Cap->getInitExpr());
  3265. continue;
  3266. } else if (Cap->isVLATypeCapture()) {
  3267. Captures.push_back(
  3268. CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
  3269. CaptureInits.push_back(nullptr);
  3270. continue;
  3271. }
  3272. assert(Cap->isReferenceCapture() &&
  3273. "non-reference capture not yet implemented");
  3274. Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
  3275. CapturedStmt::VCK_ByRef,
  3276. Cap->getVariable()));
  3277. CaptureInits.push_back(Cap->getInitExpr());
  3278. }
  3279. }
  3280. void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
  3281. CapturedRegionKind Kind,
  3282. unsigned NumParams) {
  3283. CapturedDecl *CD = nullptr;
  3284. RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
  3285. // Build the context parameter
  3286. DeclContext *DC = CapturedDecl::castToDeclContext(CD);
  3287. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3288. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
  3289. ImplicitParamDecl *Param
  3290. = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
  3291. DC->addDecl(Param);
  3292. CD->setContextParam(0, Param);
  3293. // Enter the capturing scope for this captured region.
  3294. PushCapturedRegionScope(CurScope, CD, RD, Kind);
  3295. if (CurScope)
  3296. PushDeclContext(CurScope, CD);
  3297. else
  3298. CurContext = CD;
  3299. PushExpressionEvaluationContext(PotentiallyEvaluated);
  3300. }
  3301. void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
  3302. CapturedRegionKind Kind,
  3303. ArrayRef<CapturedParamNameType> Params) {
  3304. CapturedDecl *CD = nullptr;
  3305. RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
  3306. // Build the context parameter
  3307. DeclContext *DC = CapturedDecl::castToDeclContext(CD);
  3308. bool ContextIsFound = false;
  3309. unsigned ParamNum = 0;
  3310. for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
  3311. E = Params.end();
  3312. I != E; ++I, ++ParamNum) {
  3313. if (I->second.isNull()) {
  3314. assert(!ContextIsFound &&
  3315. "null type has been found already for '__context' parameter");
  3316. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3317. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
  3318. ImplicitParamDecl *Param
  3319. = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
  3320. DC->addDecl(Param);
  3321. CD->setContextParam(ParamNum, Param);
  3322. ContextIsFound = true;
  3323. } else {
  3324. IdentifierInfo *ParamName = &Context.Idents.get(I->first);
  3325. ImplicitParamDecl *Param
  3326. = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
  3327. DC->addDecl(Param);
  3328. CD->setParam(ParamNum, Param);
  3329. }
  3330. }
  3331. assert(ContextIsFound && "no null type for '__context' parameter");
  3332. if (!ContextIsFound) {
  3333. // Add __context implicitly if it is not specified.
  3334. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3335. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
  3336. ImplicitParamDecl *Param =
  3337. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
  3338. DC->addDecl(Param);
  3339. CD->setContextParam(ParamNum, Param);
  3340. }
  3341. // Enter the capturing scope for this captured region.
  3342. PushCapturedRegionScope(CurScope, CD, RD, Kind);
  3343. if (CurScope)
  3344. PushDeclContext(CurScope, CD);
  3345. else
  3346. CurContext = CD;
  3347. PushExpressionEvaluationContext(PotentiallyEvaluated);
  3348. }
  3349. void Sema::ActOnCapturedRegionError() {
  3350. DiscardCleanupsInEvaluationContext();
  3351. PopExpressionEvaluationContext();
  3352. CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
  3353. RecordDecl *Record = RSI->TheRecordDecl;
  3354. Record->setInvalidDecl();
  3355. SmallVector<Decl*, 4> Fields(Record->fields());
  3356. ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
  3357. SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
  3358. PopDeclContext();
  3359. PopFunctionScopeInfo();
  3360. }
  3361. StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
  3362. CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
  3363. SmallVector<CapturedStmt::Capture, 4> Captures;
  3364. SmallVector<Expr *, 4> CaptureInits;
  3365. buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
  3366. CapturedDecl *CD = RSI->TheCapturedDecl;
  3367. RecordDecl *RD = RSI->TheRecordDecl;
  3368. CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
  3369. RSI->CapRegionKind, Captures,
  3370. CaptureInits, CD, RD);
  3371. CD->setBody(Res->getCapturedStmt());
  3372. RD->completeDefinition();
  3373. DiscardCleanupsInEvaluationContext();
  3374. PopExpressionEvaluationContext();
  3375. PopDeclContext();
  3376. PopFunctionScopeInfo();
  3377. return Res;
  3378. }
  3379. // HLSL Change: adding hlsl support
  3380. StmtResult Sema::ActOnHlslDiscardStmt(SourceLocation Loc)
  3381. {
  3382. return new (Context)DiscardStmt(Loc);
  3383. }