CGStmt.cpp 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  1. //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Stmt nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenFunction.h"
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenModule.h"
  15. #include "TargetInfo.h"
  16. #include "clang/AST/StmtVisitor.h"
  17. #include "clang/Basic/Builtins.h"
  18. #include "clang/Basic/PrettyStackTrace.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/InlineAsm.h"
  23. #include "llvm/IR/Intrinsics.h"
  24. #include "llvm/IR/MDBuilder.h"
  25. using namespace clang;
  26. using namespace CodeGen;
  27. //===----------------------------------------------------------------------===//
  28. // Statement Emission
  29. //===----------------------------------------------------------------------===//
  30. void CodeGenFunction::EmitStopPoint(const Stmt *S) {
  31. if (CGDebugInfo *DI = getDebugInfo()) {
  32. SourceLocation Loc;
  33. Loc = S->getBeginLoc();
  34. DI->EmitLocation(Builder, Loc);
  35. LastStopPoint = Loc;
  36. }
  37. }
  38. void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) {
  39. assert(S && "Null statement?");
  40. PGO.setCurrentStmt(S);
  41. // These statements have their own debug info handling.
  42. if (EmitSimpleStmt(S))
  43. return;
  44. // Check if we are generating unreachable code.
  45. if (!HaveInsertPoint()) {
  46. // If so, and the statement doesn't contain a label, then we do not need to
  47. // generate actual code. This is safe because (1) the current point is
  48. // unreachable, so we don't need to execute the code, and (2) we've already
  49. // handled the statements which update internal data structures (like the
  50. // local variable map) which could be used by subsequent statements.
  51. if (!ContainsLabel(S)) {
  52. // Verify that any decl statements were handled as simple, they may be in
  53. // scope of subsequent reachable statements.
  54. assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
  55. return;
  56. }
  57. // Otherwise, make a new block to hold the code.
  58. EnsureInsertPoint();
  59. }
  60. // Generate a stoppoint if we are emitting debug info.
  61. EmitStopPoint(S);
  62. // Ignore all OpenMP directives except for simd if OpenMP with Simd is
  63. // enabled.
  64. if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
  65. if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) {
  66. EmitSimpleOMPExecutableDirective(*D);
  67. return;
  68. }
  69. }
  70. switch (S->getStmtClass()) {
  71. case Stmt::NoStmtClass:
  72. case Stmt::CXXCatchStmtClass:
  73. case Stmt::SEHExceptStmtClass:
  74. case Stmt::SEHFinallyStmtClass:
  75. case Stmt::MSDependentExistsStmtClass:
  76. llvm_unreachable("invalid statement class to emit generically");
  77. case Stmt::NullStmtClass:
  78. case Stmt::CompoundStmtClass:
  79. case Stmt::DeclStmtClass:
  80. case Stmt::LabelStmtClass:
  81. case Stmt::AttributedStmtClass:
  82. case Stmt::GotoStmtClass:
  83. case Stmt::BreakStmtClass:
  84. case Stmt::ContinueStmtClass:
  85. case Stmt::DefaultStmtClass:
  86. case Stmt::CaseStmtClass:
  87. case Stmt::SEHLeaveStmtClass:
  88. llvm_unreachable("should have emitted these statements as simple");
  89. #define STMT(Type, Base)
  90. #define ABSTRACT_STMT(Op)
  91. #define EXPR(Type, Base) \
  92. case Stmt::Type##Class:
  93. #include "clang/AST/StmtNodes.inc"
  94. {
  95. // Remember the block we came in on.
  96. llvm::BasicBlock *incoming = Builder.GetInsertBlock();
  97. assert(incoming && "expression emission must have an insertion point");
  98. EmitIgnoredExpr(cast<Expr>(S));
  99. llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
  100. assert(outgoing && "expression emission cleared block!");
  101. // The expression emitters assume (reasonably!) that the insertion
  102. // point is always set. To maintain that, the call-emission code
  103. // for noreturn functions has to enter a new block with no
  104. // predecessors. We want to kill that block and mark the current
  105. // insertion point unreachable in the common case of a call like
  106. // "exit();". Since expression emission doesn't otherwise create
  107. // blocks with no predecessors, we can just test for that.
  108. // However, we must be careful not to do this to our incoming
  109. // block, because *statement* emission does sometimes create
  110. // reachable blocks which will have no predecessors until later in
  111. // the function. This occurs with, e.g., labels that are not
  112. // reachable by fallthrough.
  113. if (incoming != outgoing && outgoing->use_empty()) {
  114. outgoing->eraseFromParent();
  115. Builder.ClearInsertionPoint();
  116. }
  117. break;
  118. }
  119. case Stmt::IndirectGotoStmtClass:
  120. EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
  121. case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
  122. case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break;
  123. case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break;
  124. case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break;
  125. case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
  126. case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
  127. case Stmt::GCCAsmStmtClass: // Intentional fall-through.
  128. case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
  129. case Stmt::CoroutineBodyStmtClass:
  130. EmitCoroutineBody(cast<CoroutineBodyStmt>(*S));
  131. break;
  132. case Stmt::CoreturnStmtClass:
  133. EmitCoreturnStmt(cast<CoreturnStmt>(*S));
  134. break;
  135. case Stmt::CapturedStmtClass: {
  136. const CapturedStmt *CS = cast<CapturedStmt>(S);
  137. EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
  138. }
  139. break;
  140. case Stmt::ObjCAtTryStmtClass:
  141. EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
  142. break;
  143. case Stmt::ObjCAtCatchStmtClass:
  144. llvm_unreachable(
  145. "@catch statements should be handled by EmitObjCAtTryStmt");
  146. case Stmt::ObjCAtFinallyStmtClass:
  147. llvm_unreachable(
  148. "@finally statements should be handled by EmitObjCAtTryStmt");
  149. case Stmt::ObjCAtThrowStmtClass:
  150. EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
  151. break;
  152. case Stmt::ObjCAtSynchronizedStmtClass:
  153. EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
  154. break;
  155. case Stmt::ObjCForCollectionStmtClass:
  156. EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
  157. break;
  158. case Stmt::ObjCAutoreleasePoolStmtClass:
  159. EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
  160. break;
  161. case Stmt::CXXTryStmtClass:
  162. EmitCXXTryStmt(cast<CXXTryStmt>(*S));
  163. break;
  164. case Stmt::CXXForRangeStmtClass:
  165. EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs);
  166. break;
  167. case Stmt::SEHTryStmtClass:
  168. EmitSEHTryStmt(cast<SEHTryStmt>(*S));
  169. break;
  170. case Stmt::OMPParallelDirectiveClass:
  171. EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
  172. break;
  173. case Stmt::OMPSimdDirectiveClass:
  174. EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
  175. break;
  176. case Stmt::OMPForDirectiveClass:
  177. EmitOMPForDirective(cast<OMPForDirective>(*S));
  178. break;
  179. case Stmt::OMPForSimdDirectiveClass:
  180. EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
  181. break;
  182. case Stmt::OMPSectionsDirectiveClass:
  183. EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
  184. break;
  185. case Stmt::OMPSectionDirectiveClass:
  186. EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
  187. break;
  188. case Stmt::OMPSingleDirectiveClass:
  189. EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
  190. break;
  191. case Stmt::OMPMasterDirectiveClass:
  192. EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
  193. break;
  194. case Stmt::OMPCriticalDirectiveClass:
  195. EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
  196. break;
  197. case Stmt::OMPParallelForDirectiveClass:
  198. EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
  199. break;
  200. case Stmt::OMPParallelForSimdDirectiveClass:
  201. EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
  202. break;
  203. case Stmt::OMPParallelSectionsDirectiveClass:
  204. EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
  205. break;
  206. case Stmt::OMPTaskDirectiveClass:
  207. EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
  208. break;
  209. case Stmt::OMPTaskyieldDirectiveClass:
  210. EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
  211. break;
  212. case Stmt::OMPBarrierDirectiveClass:
  213. EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
  214. break;
  215. case Stmt::OMPTaskwaitDirectiveClass:
  216. EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
  217. break;
  218. case Stmt::OMPTaskgroupDirectiveClass:
  219. EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
  220. break;
  221. case Stmt::OMPFlushDirectiveClass:
  222. EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
  223. break;
  224. case Stmt::OMPOrderedDirectiveClass:
  225. EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
  226. break;
  227. case Stmt::OMPAtomicDirectiveClass:
  228. EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
  229. break;
  230. case Stmt::OMPTargetDirectiveClass:
  231. EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
  232. break;
  233. case Stmt::OMPTeamsDirectiveClass:
  234. EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
  235. break;
  236. case Stmt::OMPCancellationPointDirectiveClass:
  237. EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
  238. break;
  239. case Stmt::OMPCancelDirectiveClass:
  240. EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
  241. break;
  242. case Stmt::OMPTargetDataDirectiveClass:
  243. EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
  244. break;
  245. case Stmt::OMPTargetEnterDataDirectiveClass:
  246. EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
  247. break;
  248. case Stmt::OMPTargetExitDataDirectiveClass:
  249. EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
  250. break;
  251. case Stmt::OMPTargetParallelDirectiveClass:
  252. EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
  253. break;
  254. case Stmt::OMPTargetParallelForDirectiveClass:
  255. EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
  256. break;
  257. case Stmt::OMPTaskLoopDirectiveClass:
  258. EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
  259. break;
  260. case Stmt::OMPTaskLoopSimdDirectiveClass:
  261. EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
  262. break;
  263. case Stmt::OMPDistributeDirectiveClass:
  264. EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
  265. break;
  266. case Stmt::OMPTargetUpdateDirectiveClass:
  267. EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
  268. break;
  269. case Stmt::OMPDistributeParallelForDirectiveClass:
  270. EmitOMPDistributeParallelForDirective(
  271. cast<OMPDistributeParallelForDirective>(*S));
  272. break;
  273. case Stmt::OMPDistributeParallelForSimdDirectiveClass:
  274. EmitOMPDistributeParallelForSimdDirective(
  275. cast<OMPDistributeParallelForSimdDirective>(*S));
  276. break;
  277. case Stmt::OMPDistributeSimdDirectiveClass:
  278. EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
  279. break;
  280. case Stmt::OMPTargetParallelForSimdDirectiveClass:
  281. EmitOMPTargetParallelForSimdDirective(
  282. cast<OMPTargetParallelForSimdDirective>(*S));
  283. break;
  284. case Stmt::OMPTargetSimdDirectiveClass:
  285. EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S));
  286. break;
  287. case Stmt::OMPTeamsDistributeDirectiveClass:
  288. EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S));
  289. break;
  290. case Stmt::OMPTeamsDistributeSimdDirectiveClass:
  291. EmitOMPTeamsDistributeSimdDirective(
  292. cast<OMPTeamsDistributeSimdDirective>(*S));
  293. break;
  294. case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
  295. EmitOMPTeamsDistributeParallelForSimdDirective(
  296. cast<OMPTeamsDistributeParallelForSimdDirective>(*S));
  297. break;
  298. case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
  299. EmitOMPTeamsDistributeParallelForDirective(
  300. cast<OMPTeamsDistributeParallelForDirective>(*S));
  301. break;
  302. case Stmt::OMPTargetTeamsDirectiveClass:
  303. EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S));
  304. break;
  305. case Stmt::OMPTargetTeamsDistributeDirectiveClass:
  306. EmitOMPTargetTeamsDistributeDirective(
  307. cast<OMPTargetTeamsDistributeDirective>(*S));
  308. break;
  309. case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
  310. EmitOMPTargetTeamsDistributeParallelForDirective(
  311. cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
  312. break;
  313. case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
  314. EmitOMPTargetTeamsDistributeParallelForSimdDirective(
  315. cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
  316. break;
  317. case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
  318. EmitOMPTargetTeamsDistributeSimdDirective(
  319. cast<OMPTargetTeamsDistributeSimdDirective>(*S));
  320. break;
  321. }
  322. }
  323. bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
  324. switch (S->getStmtClass()) {
  325. default: return false;
  326. case Stmt::NullStmtClass: break;
  327. case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
  328. case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
  329. case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
  330. case Stmt::AttributedStmtClass:
  331. EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
  332. case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
  333. case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
  334. case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
  335. case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
  336. case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
  337. case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
  338. }
  339. return true;
  340. }
  341. /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
  342. /// this captures the expression result of the last sub-statement and returns it
  343. /// (for use by the statement expression extension).
  344. Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
  345. AggValueSlot AggSlot) {
  346. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
  347. "LLVM IR generation of compound statement ('{}')");
  348. // Keep track of the current cleanup stack depth, including debug scopes.
  349. LexicalScope Scope(*this, S.getSourceRange());
  350. return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
  351. }
  352. Address
  353. CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  354. bool GetLast,
  355. AggValueSlot AggSlot) {
  356. const Stmt *ExprResult = S.getStmtExprResult();
  357. assert((!GetLast || (GetLast && ExprResult)) &&
  358. "If GetLast is true then the CompoundStmt must have a StmtExprResult");
  359. Address RetAlloca = Address::invalid();
  360. for (auto *CurStmt : S.body()) {
  361. if (GetLast && ExprResult == CurStmt) {
  362. // We have to special case labels here. They are statements, but when put
  363. // at the end of a statement expression, they yield the value of their
  364. // subexpression. Handle this by walking through all labels we encounter,
  365. // emitting them before we evaluate the subexpr.
  366. // Similar issues arise for attributed statements.
  367. while (!isa<Expr>(ExprResult)) {
  368. if (const auto *LS = dyn_cast<LabelStmt>(ExprResult)) {
  369. EmitLabel(LS->getDecl());
  370. ExprResult = LS->getSubStmt();
  371. } else if (const auto *AS = dyn_cast<AttributedStmt>(ExprResult)) {
  372. // FIXME: Update this if we ever have attributes that affect the
  373. // semantics of an expression.
  374. ExprResult = AS->getSubStmt();
  375. } else {
  376. llvm_unreachable("unknown value statement");
  377. }
  378. }
  379. EnsureInsertPoint();
  380. const Expr *E = cast<Expr>(ExprResult);
  381. QualType ExprTy = E->getType();
  382. if (hasAggregateEvaluationKind(ExprTy)) {
  383. EmitAggExpr(E, AggSlot);
  384. } else {
  385. // We can't return an RValue here because there might be cleanups at
  386. // the end of the StmtExpr. Because of that, we have to emit the result
  387. // here into a temporary alloca.
  388. RetAlloca = CreateMemTemp(ExprTy);
  389. EmitAnyExprToMem(E, RetAlloca, Qualifiers(),
  390. /*IsInit*/ false);
  391. }
  392. } else {
  393. EmitStmt(CurStmt);
  394. }
  395. }
  396. return RetAlloca;
  397. }
  398. void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
  399. llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
  400. // If there is a cleanup stack, then we it isn't worth trying to
  401. // simplify this block (we would need to remove it from the scope map
  402. // and cleanup entry).
  403. if (!EHStack.empty())
  404. return;
  405. // Can only simplify direct branches.
  406. if (!BI || !BI->isUnconditional())
  407. return;
  408. // Can only simplify empty blocks.
  409. if (BI->getIterator() != BB->begin())
  410. return;
  411. BB->replaceAllUsesWith(BI->getSuccessor(0));
  412. BI->eraseFromParent();
  413. BB->eraseFromParent();
  414. }
  415. void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
  416. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  417. // Fall out of the current block (if necessary).
  418. EmitBranch(BB);
  419. if (IsFinished && BB->use_empty()) {
  420. delete BB;
  421. return;
  422. }
  423. // Place the block after the current block, if possible, or else at
  424. // the end of the function.
  425. if (CurBB && CurBB->getParent())
  426. CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
  427. else
  428. CurFn->getBasicBlockList().push_back(BB);
  429. Builder.SetInsertPoint(BB);
  430. }
  431. void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
  432. // Emit a branch from the current block to the target one if this
  433. // was a real block. If this was just a fall-through block after a
  434. // terminator, don't emit it.
  435. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  436. if (!CurBB || CurBB->getTerminator()) {
  437. // If there is no insert point or the previous block is already
  438. // terminated, don't touch it.
  439. } else {
  440. // Otherwise, create a fall-through branch.
  441. Builder.CreateBr(Target);
  442. }
  443. Builder.ClearInsertionPoint();
  444. }
  445. void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
  446. bool inserted = false;
  447. for (llvm::User *u : block->users()) {
  448. if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
  449. CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
  450. block);
  451. inserted = true;
  452. break;
  453. }
  454. }
  455. if (!inserted)
  456. CurFn->getBasicBlockList().push_back(block);
  457. Builder.SetInsertPoint(block);
  458. }
  459. CodeGenFunction::JumpDest
  460. CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
  461. JumpDest &Dest = LabelMap[D];
  462. if (Dest.isValid()) return Dest;
  463. // Create, but don't insert, the new block.
  464. Dest = JumpDest(createBasicBlock(D->getName()),
  465. EHScopeStack::stable_iterator::invalid(),
  466. NextCleanupDestIndex++);
  467. return Dest;
  468. }
  469. void CodeGenFunction::EmitLabel(const LabelDecl *D) {
  470. // Add this label to the current lexical scope if we're within any
  471. // normal cleanups. Jumps "in" to this label --- when permitted by
  472. // the language --- may need to be routed around such cleanups.
  473. if (EHStack.hasNormalCleanups() && CurLexicalScope)
  474. CurLexicalScope->addLabel(D);
  475. JumpDest &Dest = LabelMap[D];
  476. // If we didn't need a forward reference to this label, just go
  477. // ahead and create a destination at the current scope.
  478. if (!Dest.isValid()) {
  479. Dest = getJumpDestInCurrentScope(D->getName());
  480. // Otherwise, we need to give this label a target depth and remove
  481. // it from the branch-fixups list.
  482. } else {
  483. assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
  484. Dest.setScopeDepth(EHStack.stable_begin());
  485. ResolveBranchFixups(Dest.getBlock());
  486. }
  487. EmitBlock(Dest.getBlock());
  488. // Emit debug info for labels.
  489. if (CGDebugInfo *DI = getDebugInfo()) {
  490. if (CGM.getCodeGenOpts().getDebugInfo() >=
  491. codegenoptions::LimitedDebugInfo) {
  492. DI->setLocation(D->getLocation());
  493. DI->EmitLabel(D, Builder);
  494. }
  495. }
  496. incrementProfileCounter(D->getStmt());
  497. }
  498. /// Change the cleanup scope of the labels in this lexical scope to
  499. /// match the scope of the enclosing context.
  500. void CodeGenFunction::LexicalScope::rescopeLabels() {
  501. assert(!Labels.empty());
  502. EHScopeStack::stable_iterator innermostScope
  503. = CGF.EHStack.getInnermostNormalCleanup();
  504. // Change the scope depth of all the labels.
  505. for (SmallVectorImpl<const LabelDecl*>::const_iterator
  506. i = Labels.begin(), e = Labels.end(); i != e; ++i) {
  507. assert(CGF.LabelMap.count(*i));
  508. JumpDest &dest = CGF.LabelMap.find(*i)->second;
  509. assert(dest.getScopeDepth().isValid());
  510. assert(innermostScope.encloses(dest.getScopeDepth()));
  511. dest.setScopeDepth(innermostScope);
  512. }
  513. // Reparent the labels if the new scope also has cleanups.
  514. if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
  515. ParentScope->Labels.append(Labels.begin(), Labels.end());
  516. }
  517. }
  518. void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
  519. EmitLabel(S.getDecl());
  520. EmitStmt(S.getSubStmt());
  521. }
  522. void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
  523. EmitStmt(S.getSubStmt(), S.getAttrs());
  524. }
  525. void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
  526. // If this code is reachable then emit a stop point (if generating
  527. // debug info). We have to do this ourselves because we are on the
  528. // "simple" statement path.
  529. if (HaveInsertPoint())
  530. EmitStopPoint(&S);
  531. EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
  532. }
  533. void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
  534. if (const LabelDecl *Target = S.getConstantTarget()) {
  535. EmitBranchThroughCleanup(getJumpDestForLabel(Target));
  536. return;
  537. }
  538. // Ensure that we have an i8* for our PHI node.
  539. llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
  540. Int8PtrTy, "addr");
  541. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  542. // Get the basic block for the indirect goto.
  543. llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
  544. // The first instruction in the block has to be the PHI for the switch dest,
  545. // add an entry for this branch.
  546. cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
  547. EmitBranch(IndGotoBB);
  548. }
  549. void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
  550. // C99 6.8.4.1: The first substatement is executed if the expression compares
  551. // unequal to 0. The condition must be a scalar type.
  552. LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
  553. if (S.getInit())
  554. EmitStmt(S.getInit());
  555. if (S.getConditionVariable())
  556. EmitDecl(*S.getConditionVariable());
  557. // If the condition constant folds and can be elided, try to avoid emitting
  558. // the condition and the dead arm of the if/else.
  559. bool CondConstant;
  560. if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
  561. S.isConstexpr())) {
  562. // Figure out which block (then or else) is executed.
  563. const Stmt *Executed = S.getThen();
  564. const Stmt *Skipped = S.getElse();
  565. if (!CondConstant) // Condition false?
  566. std::swap(Executed, Skipped);
  567. // If the skipped block has no labels in it, just emit the executed block.
  568. // This avoids emitting dead code and simplifies the CFG substantially.
  569. if (S.isConstexpr() || !ContainsLabel(Skipped)) {
  570. if (CondConstant)
  571. incrementProfileCounter(&S);
  572. if (Executed) {
  573. RunCleanupsScope ExecutedScope(*this);
  574. EmitStmt(Executed);
  575. }
  576. return;
  577. }
  578. }
  579. // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
  580. // the conditional branch.
  581. llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
  582. llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
  583. llvm::BasicBlock *ElseBlock = ContBlock;
  584. if (S.getElse())
  585. ElseBlock = createBasicBlock("if.else");
  586. EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
  587. getProfileCount(S.getThen()));
  588. // Emit the 'then' code.
  589. EmitBlock(ThenBlock);
  590. incrementProfileCounter(&S);
  591. {
  592. RunCleanupsScope ThenScope(*this);
  593. EmitStmt(S.getThen());
  594. }
  595. EmitBranch(ContBlock);
  596. // Emit the 'else' code if present.
  597. if (const Stmt *Else = S.getElse()) {
  598. {
  599. // There is no need to emit line number for an unconditional branch.
  600. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  601. EmitBlock(ElseBlock);
  602. }
  603. {
  604. RunCleanupsScope ElseScope(*this);
  605. EmitStmt(Else);
  606. }
  607. {
  608. // There is no need to emit line number for an unconditional branch.
  609. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  610. EmitBranch(ContBlock);
  611. }
  612. }
  613. // Emit the continuation block for code after the if.
  614. EmitBlock(ContBlock, true);
  615. }
  616. void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
  617. ArrayRef<const Attr *> WhileAttrs) {
  618. // Emit the header for the loop, which will also become
  619. // the continue target.
  620. JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
  621. EmitBlock(LoopHeader.getBlock());
  622. const SourceRange &R = S.getSourceRange();
  623. LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), WhileAttrs,
  624. SourceLocToDebugLoc(R.getBegin()),
  625. SourceLocToDebugLoc(R.getEnd()));
  626. // Create an exit block for when the condition fails, which will
  627. // also become the break target.
  628. JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
  629. // Store the blocks to use for break and continue.
  630. BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
  631. // C++ [stmt.while]p2:
  632. // When the condition of a while statement is a declaration, the
  633. // scope of the variable that is declared extends from its point
  634. // of declaration (3.3.2) to the end of the while statement.
  635. // [...]
  636. // The object created in a condition is destroyed and created
  637. // with each iteration of the loop.
  638. RunCleanupsScope ConditionScope(*this);
  639. if (S.getConditionVariable())
  640. EmitDecl(*S.getConditionVariable());
  641. // Evaluate the conditional in the while header. C99 6.8.5.1: The
  642. // evaluation of the controlling expression takes place before each
  643. // execution of the loop body.
  644. llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
  645. // while(1) is common, avoid extra exit blocks. Be sure
  646. // to correctly handle break/continue though.
  647. bool EmitBoolCondBranch = true;
  648. if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
  649. if (C->isOne())
  650. EmitBoolCondBranch = false;
  651. // As long as the condition is true, go to the loop body.
  652. llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
  653. if (EmitBoolCondBranch) {
  654. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  655. if (ConditionScope.requiresCleanups())
  656. ExitBlock = createBasicBlock("while.exit");
  657. Builder.CreateCondBr(
  658. BoolCondVal, LoopBody, ExitBlock,
  659. createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
  660. if (ExitBlock != LoopExit.getBlock()) {
  661. EmitBlock(ExitBlock);
  662. EmitBranchThroughCleanup(LoopExit);
  663. }
  664. }
  665. // Emit the loop body. We have to emit this in a cleanup scope
  666. // because it might be a singleton DeclStmt.
  667. {
  668. RunCleanupsScope BodyScope(*this);
  669. EmitBlock(LoopBody);
  670. incrementProfileCounter(&S);
  671. EmitStmt(S.getBody());
  672. }
  673. BreakContinueStack.pop_back();
  674. // Immediately force cleanup.
  675. ConditionScope.ForceCleanup();
  676. EmitStopPoint(&S);
  677. // Branch to the loop header again.
  678. EmitBranch(LoopHeader.getBlock());
  679. LoopStack.pop();
  680. // Emit the exit block.
  681. EmitBlock(LoopExit.getBlock(), true);
  682. // The LoopHeader typically is just a branch if we skipped emitting
  683. // a branch, try to erase it.
  684. if (!EmitBoolCondBranch)
  685. SimplifyForwardingBlocks(LoopHeader.getBlock());
  686. }
  687. void CodeGenFunction::EmitDoStmt(const DoStmt &S,
  688. ArrayRef<const Attr *> DoAttrs) {
  689. JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
  690. JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
  691. uint64_t ParentCount = getCurrentProfileCount();
  692. // Store the blocks to use for break and continue.
  693. BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
  694. // Emit the body of the loop.
  695. llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
  696. EmitBlockWithFallThrough(LoopBody, &S);
  697. {
  698. RunCleanupsScope BodyScope(*this);
  699. EmitStmt(S.getBody());
  700. }
  701. EmitBlock(LoopCond.getBlock());
  702. const SourceRange &R = S.getSourceRange();
  703. LoopStack.push(LoopBody, CGM.getContext(), DoAttrs,
  704. SourceLocToDebugLoc(R.getBegin()),
  705. SourceLocToDebugLoc(R.getEnd()));
  706. // C99 6.8.5.2: "The evaluation of the controlling expression takes place
  707. // after each execution of the loop body."
  708. // Evaluate the conditional in the while header.
  709. // C99 6.8.5p2/p4: The first substatement is executed if the expression
  710. // compares unequal to 0. The condition must be a scalar type.
  711. llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
  712. BreakContinueStack.pop_back();
  713. // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
  714. // to correctly handle break/continue though.
  715. bool EmitBoolCondBranch = true;
  716. if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
  717. if (C->isZero())
  718. EmitBoolCondBranch = false;
  719. // As long as the condition is true, iterate the loop.
  720. if (EmitBoolCondBranch) {
  721. uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
  722. Builder.CreateCondBr(
  723. BoolCondVal, LoopBody, LoopExit.getBlock(),
  724. createProfileWeightsForLoop(S.getCond(), BackedgeCount));
  725. }
  726. LoopStack.pop();
  727. // Emit the exit block.
  728. EmitBlock(LoopExit.getBlock());
  729. // The DoCond block typically is just a branch if we skipped
  730. // emitting a branch, try to erase it.
  731. if (!EmitBoolCondBranch)
  732. SimplifyForwardingBlocks(LoopCond.getBlock());
  733. }
  734. void CodeGenFunction::EmitForStmt(const ForStmt &S,
  735. ArrayRef<const Attr *> ForAttrs) {
  736. JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
  737. LexicalScope ForScope(*this, S.getSourceRange());
  738. // Evaluate the first part before the loop.
  739. if (S.getInit())
  740. EmitStmt(S.getInit());
  741. // Start the loop with a block that tests the condition.
  742. // If there's an increment, the continue scope will be overwritten
  743. // later.
  744. JumpDest Continue = getJumpDestInCurrentScope("for.cond");
  745. llvm::BasicBlock *CondBlock = Continue.getBlock();
  746. EmitBlock(CondBlock);
  747. const SourceRange &R = S.getSourceRange();
  748. LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
  749. SourceLocToDebugLoc(R.getBegin()),
  750. SourceLocToDebugLoc(R.getEnd()));
  751. // If the for loop doesn't have an increment we can just use the
  752. // condition as the continue block. Otherwise we'll need to create
  753. // a block for it (in the current scope, i.e. in the scope of the
  754. // condition), and that we will become our continue block.
  755. if (S.getInc())
  756. Continue = getJumpDestInCurrentScope("for.inc");
  757. // Store the blocks to use for break and continue.
  758. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  759. // Create a cleanup scope for the condition variable cleanups.
  760. LexicalScope ConditionScope(*this, S.getSourceRange());
  761. if (S.getCond()) {
  762. // If the for statement has a condition scope, emit the local variable
  763. // declaration.
  764. if (S.getConditionVariable()) {
  765. EmitDecl(*S.getConditionVariable());
  766. }
  767. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  768. // If there are any cleanups between here and the loop-exit scope,
  769. // create a block to stage a loop exit along.
  770. if (ForScope.requiresCleanups())
  771. ExitBlock = createBasicBlock("for.cond.cleanup");
  772. // As long as the condition is true, iterate the loop.
  773. llvm::BasicBlock *ForBody = createBasicBlock("for.body");
  774. // C99 6.8.5p2/p4: The first substatement is executed if the expression
  775. // compares unequal to 0. The condition must be a scalar type.
  776. llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
  777. Builder.CreateCondBr(
  778. BoolCondVal, ForBody, ExitBlock,
  779. createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
  780. if (ExitBlock != LoopExit.getBlock()) {
  781. EmitBlock(ExitBlock);
  782. EmitBranchThroughCleanup(LoopExit);
  783. }
  784. EmitBlock(ForBody);
  785. } else {
  786. // Treat it as a non-zero constant. Don't even create a new block for the
  787. // body, just fall into it.
  788. }
  789. incrementProfileCounter(&S);
  790. {
  791. // Create a separate cleanup scope for the body, in case it is not
  792. // a compound statement.
  793. RunCleanupsScope BodyScope(*this);
  794. EmitStmt(S.getBody());
  795. }
  796. // If there is an increment, emit it next.
  797. if (S.getInc()) {
  798. EmitBlock(Continue.getBlock());
  799. EmitStmt(S.getInc());
  800. }
  801. BreakContinueStack.pop_back();
  802. ConditionScope.ForceCleanup();
  803. EmitStopPoint(&S);
  804. EmitBranch(CondBlock);
  805. ForScope.ForceCleanup();
  806. LoopStack.pop();
  807. // Emit the fall-through block.
  808. EmitBlock(LoopExit.getBlock(), true);
  809. }
  810. void
  811. CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  812. ArrayRef<const Attr *> ForAttrs) {
  813. JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
  814. LexicalScope ForScope(*this, S.getSourceRange());
  815. // Evaluate the first pieces before the loop.
  816. if (S.getInit())
  817. EmitStmt(S.getInit());
  818. EmitStmt(S.getRangeStmt());
  819. EmitStmt(S.getBeginStmt());
  820. EmitStmt(S.getEndStmt());
  821. // Start the loop with a block that tests the condition.
  822. // If there's an increment, the continue scope will be overwritten
  823. // later.
  824. llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
  825. EmitBlock(CondBlock);
  826. const SourceRange &R = S.getSourceRange();
  827. LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
  828. SourceLocToDebugLoc(R.getBegin()),
  829. SourceLocToDebugLoc(R.getEnd()));
  830. // If there are any cleanups between here and the loop-exit scope,
  831. // create a block to stage a loop exit along.
  832. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  833. if (ForScope.requiresCleanups())
  834. ExitBlock = createBasicBlock("for.cond.cleanup");
  835. // The loop body, consisting of the specified body and the loop variable.
  836. llvm::BasicBlock *ForBody = createBasicBlock("for.body");
  837. // The body is executed if the expression, contextually converted
  838. // to bool, is true.
  839. llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
  840. Builder.CreateCondBr(
  841. BoolCondVal, ForBody, ExitBlock,
  842. createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
  843. if (ExitBlock != LoopExit.getBlock()) {
  844. EmitBlock(ExitBlock);
  845. EmitBranchThroughCleanup(LoopExit);
  846. }
  847. EmitBlock(ForBody);
  848. incrementProfileCounter(&S);
  849. // Create a block for the increment. In case of a 'continue', we jump there.
  850. JumpDest Continue = getJumpDestInCurrentScope("for.inc");
  851. // Store the blocks to use for break and continue.
  852. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  853. {
  854. // Create a separate cleanup scope for the loop variable and body.
  855. LexicalScope BodyScope(*this, S.getSourceRange());
  856. EmitStmt(S.getLoopVarStmt());
  857. EmitStmt(S.getBody());
  858. }
  859. EmitStopPoint(&S);
  860. // If there is an increment, emit it next.
  861. EmitBlock(Continue.getBlock());
  862. EmitStmt(S.getInc());
  863. BreakContinueStack.pop_back();
  864. EmitBranch(CondBlock);
  865. ForScope.ForceCleanup();
  866. LoopStack.pop();
  867. // Emit the fall-through block.
  868. EmitBlock(LoopExit.getBlock(), true);
  869. }
  870. void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
  871. if (RV.isScalar()) {
  872. Builder.CreateStore(RV.getScalarVal(), ReturnValue);
  873. } else if (RV.isAggregate()) {
  874. LValue Dest = MakeAddrLValue(ReturnValue, Ty);
  875. LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty);
  876. EmitAggregateCopy(Dest, Src, Ty, getOverlapForReturnValue());
  877. } else {
  878. EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
  879. /*init*/ true);
  880. }
  881. EmitBranchThroughCleanup(ReturnBlock);
  882. }
  883. /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
  884. /// if the function returns void, or may be missing one if the function returns
  885. /// non-void. Fun stuff :).
  886. void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
  887. if (requiresReturnValueCheck()) {
  888. llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
  889. auto *SLocPtr =
  890. new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
  891. llvm::GlobalVariable::PrivateLinkage, SLoc);
  892. SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  893. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
  894. assert(ReturnLocation.isValid() && "No valid return location");
  895. Builder.CreateStore(Builder.CreateBitCast(SLocPtr, Int8PtrTy),
  896. ReturnLocation);
  897. }
  898. // Returning from an outlined SEH helper is UB, and we already warn on it.
  899. if (IsOutlinedSEHHelper) {
  900. Builder.CreateUnreachable();
  901. Builder.ClearInsertionPoint();
  902. }
  903. // Emit the result value, even if unused, to evaluate the side effects.
  904. const Expr *RV = S.getRetValue();
  905. // Treat block literals in a return expression as if they appeared
  906. // in their own scope. This permits a small, easily-implemented
  907. // exception to our over-conservative rules about not jumping to
  908. // statements following block literals with non-trivial cleanups.
  909. RunCleanupsScope cleanupScope(*this);
  910. if (const FullExpr *fe = dyn_cast_or_null<FullExpr>(RV)) {
  911. enterFullExpression(fe);
  912. RV = fe->getSubExpr();
  913. }
  914. // FIXME: Clean this up by using an LValue for ReturnTemp,
  915. // EmitStoreThroughLValue, and EmitAnyExpr.
  916. if (getLangOpts().ElideConstructors &&
  917. S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
  918. // Apply the named return value optimization for this return statement,
  919. // which means doing nothing: the appropriate result has already been
  920. // constructed into the NRVO variable.
  921. // If there is an NRVO flag for this variable, set it to 1 into indicate
  922. // that the cleanup code should not destroy the variable.
  923. if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
  924. Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
  925. } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
  926. // Make sure not to return anything, but evaluate the expression
  927. // for side effects.
  928. if (RV)
  929. EmitAnyExpr(RV);
  930. } else if (!RV) {
  931. // Do nothing (return value is left uninitialized)
  932. } else if (FnRetTy->isReferenceType()) {
  933. // If this function returns a reference, take the address of the expression
  934. // rather than the value.
  935. RValue Result = EmitReferenceBindingToExpr(RV);
  936. Builder.CreateStore(Result.getScalarVal(), ReturnValue);
  937. } else {
  938. switch (getEvaluationKind(RV->getType())) {
  939. case TEK_Scalar:
  940. Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
  941. break;
  942. case TEK_Complex:
  943. EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
  944. /*isInit*/ true);
  945. break;
  946. case TEK_Aggregate:
  947. EmitAggExpr(RV, AggValueSlot::forAddr(
  948. ReturnValue, Qualifiers(),
  949. AggValueSlot::IsDestructed,
  950. AggValueSlot::DoesNotNeedGCBarriers,
  951. AggValueSlot::IsNotAliased,
  952. getOverlapForReturnValue()));
  953. break;
  954. }
  955. }
  956. ++NumReturnExprs;
  957. if (!RV || RV->isEvaluatable(getContext()))
  958. ++NumSimpleReturnExprs;
  959. cleanupScope.ForceCleanup();
  960. EmitBranchThroughCleanup(ReturnBlock);
  961. }
  962. void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
  963. // As long as debug info is modeled with instructions, we have to ensure we
  964. // have a place to insert here and write the stop point here.
  965. if (HaveInsertPoint())
  966. EmitStopPoint(&S);
  967. for (const auto *I : S.decls())
  968. EmitDecl(*I);
  969. }
  970. void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
  971. assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
  972. // If this code is reachable then emit a stop point (if generating
  973. // debug info). We have to do this ourselves because we are on the
  974. // "simple" statement path.
  975. if (HaveInsertPoint())
  976. EmitStopPoint(&S);
  977. EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
  978. }
  979. void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
  980. assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
  981. // If this code is reachable then emit a stop point (if generating
  982. // debug info). We have to do this ourselves because we are on the
  983. // "simple" statement path.
  984. if (HaveInsertPoint())
  985. EmitStopPoint(&S);
  986. EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
  987. }
  988. /// EmitCaseStmtRange - If case statement range is not too big then
  989. /// add multiple cases to switch instruction, one for each value within
  990. /// the range. If range is too big then emit "if" condition check.
  991. void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
  992. assert(S.getRHS() && "Expected RHS value in CaseStmt");
  993. llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
  994. llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
  995. // Emit the code for this case. We do this first to make sure it is
  996. // properly chained from our predecessor before generating the
  997. // switch machinery to enter this block.
  998. llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
  999. EmitBlockWithFallThrough(CaseDest, &S);
  1000. EmitStmt(S.getSubStmt());
  1001. // If range is empty, do nothing.
  1002. if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
  1003. return;
  1004. llvm::APInt Range = RHS - LHS;
  1005. // FIXME: parameters such as this should not be hardcoded.
  1006. if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
  1007. // Range is small enough to add multiple switch instruction cases.
  1008. uint64_t Total = getProfileCount(&S);
  1009. unsigned NCases = Range.getZExtValue() + 1;
  1010. // We only have one region counter for the entire set of cases here, so we
  1011. // need to divide the weights evenly between the generated cases, ensuring
  1012. // that the total weight is preserved. E.g., a weight of 5 over three cases
  1013. // will be distributed as weights of 2, 2, and 1.
  1014. uint64_t Weight = Total / NCases, Rem = Total % NCases;
  1015. for (unsigned I = 0; I != NCases; ++I) {
  1016. if (SwitchWeights)
  1017. SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
  1018. if (Rem)
  1019. Rem--;
  1020. SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
  1021. ++LHS;
  1022. }
  1023. return;
  1024. }
  1025. // The range is too big. Emit "if" condition into a new block,
  1026. // making sure to save and restore the current insertion point.
  1027. llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
  1028. // Push this test onto the chain of range checks (which terminates
  1029. // in the default basic block). The switch's default will be changed
  1030. // to the top of this chain after switch emission is complete.
  1031. llvm::BasicBlock *FalseDest = CaseRangeBlock;
  1032. CaseRangeBlock = createBasicBlock("sw.caserange");
  1033. CurFn->getBasicBlockList().push_back(CaseRangeBlock);
  1034. Builder.SetInsertPoint(CaseRangeBlock);
  1035. // Emit range check.
  1036. llvm::Value *Diff =
  1037. Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
  1038. llvm::Value *Cond =
  1039. Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
  1040. llvm::MDNode *Weights = nullptr;
  1041. if (SwitchWeights) {
  1042. uint64_t ThisCount = getProfileCount(&S);
  1043. uint64_t DefaultCount = (*SwitchWeights)[0];
  1044. Weights = createProfileWeights(ThisCount, DefaultCount);
  1045. // Since we're chaining the switch default through each large case range, we
  1046. // need to update the weight for the default, ie, the first case, to include
  1047. // this case.
  1048. (*SwitchWeights)[0] += ThisCount;
  1049. }
  1050. Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
  1051. // Restore the appropriate insertion point.
  1052. if (RestoreBB)
  1053. Builder.SetInsertPoint(RestoreBB);
  1054. else
  1055. Builder.ClearInsertionPoint();
  1056. }
  1057. void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
  1058. // If there is no enclosing switch instance that we're aware of, then this
  1059. // case statement and its block can be elided. This situation only happens
  1060. // when we've constant-folded the switch, are emitting the constant case,
  1061. // and part of the constant case includes another case statement. For
  1062. // instance: switch (4) { case 4: do { case 5: } while (1); }
  1063. if (!SwitchInsn) {
  1064. EmitStmt(S.getSubStmt());
  1065. return;
  1066. }
  1067. // Handle case ranges.
  1068. if (S.getRHS()) {
  1069. EmitCaseStmtRange(S);
  1070. return;
  1071. }
  1072. llvm::ConstantInt *CaseVal =
  1073. Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
  1074. // If the body of the case is just a 'break', try to not emit an empty block.
  1075. // If we're profiling or we're not optimizing, leave the block in for better
  1076. // debug and coverage analysis.
  1077. if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
  1078. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1079. isa<BreakStmt>(S.getSubStmt())) {
  1080. JumpDest Block = BreakContinueStack.back().BreakBlock;
  1081. // Only do this optimization if there are no cleanups that need emitting.
  1082. if (isObviouslyBranchWithoutCleanups(Block)) {
  1083. if (SwitchWeights)
  1084. SwitchWeights->push_back(getProfileCount(&S));
  1085. SwitchInsn->addCase(CaseVal, Block.getBlock());
  1086. // If there was a fallthrough into this case, make sure to redirect it to
  1087. // the end of the switch as well.
  1088. if (Builder.GetInsertBlock()) {
  1089. Builder.CreateBr(Block.getBlock());
  1090. Builder.ClearInsertionPoint();
  1091. }
  1092. return;
  1093. }
  1094. }
  1095. llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
  1096. EmitBlockWithFallThrough(CaseDest, &S);
  1097. if (SwitchWeights)
  1098. SwitchWeights->push_back(getProfileCount(&S));
  1099. SwitchInsn->addCase(CaseVal, CaseDest);
  1100. // Recursively emitting the statement is acceptable, but is not wonderful for
  1101. // code where we have many case statements nested together, i.e.:
  1102. // case 1:
  1103. // case 2:
  1104. // case 3: etc.
  1105. // Handling this recursively will create a new block for each case statement
  1106. // that falls through to the next case which is IR intensive. It also causes
  1107. // deep recursion which can run into stack depth limitations. Handle
  1108. // sequential non-range case statements specially.
  1109. const CaseStmt *CurCase = &S;
  1110. const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
  1111. // Otherwise, iteratively add consecutive cases to this switch stmt.
  1112. while (NextCase && NextCase->getRHS() == nullptr) {
  1113. CurCase = NextCase;
  1114. llvm::ConstantInt *CaseVal =
  1115. Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
  1116. if (SwitchWeights)
  1117. SwitchWeights->push_back(getProfileCount(NextCase));
  1118. if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
  1119. CaseDest = createBasicBlock("sw.bb");
  1120. EmitBlockWithFallThrough(CaseDest, &S);
  1121. }
  1122. SwitchInsn->addCase(CaseVal, CaseDest);
  1123. NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
  1124. }
  1125. // Normal default recursion for non-cases.
  1126. EmitStmt(CurCase->getSubStmt());
  1127. }
  1128. void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
  1129. // If there is no enclosing switch instance that we're aware of, then this
  1130. // default statement can be elided. This situation only happens when we've
  1131. // constant-folded the switch.
  1132. if (!SwitchInsn) {
  1133. EmitStmt(S.getSubStmt());
  1134. return;
  1135. }
  1136. llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
  1137. assert(DefaultBlock->empty() &&
  1138. "EmitDefaultStmt: Default block already defined?");
  1139. EmitBlockWithFallThrough(DefaultBlock, &S);
  1140. EmitStmt(S.getSubStmt());
  1141. }
  1142. /// CollectStatementsForCase - Given the body of a 'switch' statement and a
  1143. /// constant value that is being switched on, see if we can dead code eliminate
  1144. /// the body of the switch to a simple series of statements to emit. Basically,
  1145. /// on a switch (5) we want to find these statements:
  1146. /// case 5:
  1147. /// printf(...); <--
  1148. /// ++i; <--
  1149. /// break;
  1150. ///
  1151. /// and add them to the ResultStmts vector. If it is unsafe to do this
  1152. /// transformation (for example, one of the elided statements contains a label
  1153. /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
  1154. /// should include statements after it (e.g. the printf() line is a substmt of
  1155. /// the case) then return CSFC_FallThrough. If we handled it and found a break
  1156. /// statement, then return CSFC_Success.
  1157. ///
  1158. /// If Case is non-null, then we are looking for the specified case, checking
  1159. /// that nothing we jump over contains labels. If Case is null, then we found
  1160. /// the case and are looking for the break.
  1161. ///
  1162. /// If the recursive walk actually finds our Case, then we set FoundCase to
  1163. /// true.
  1164. ///
  1165. enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
  1166. static CSFC_Result CollectStatementsForCase(const Stmt *S,
  1167. const SwitchCase *Case,
  1168. bool &FoundCase,
  1169. SmallVectorImpl<const Stmt*> &ResultStmts) {
  1170. // If this is a null statement, just succeed.
  1171. if (!S)
  1172. return Case ? CSFC_Success : CSFC_FallThrough;
  1173. // If this is the switchcase (case 4: or default) that we're looking for, then
  1174. // we're in business. Just add the substatement.
  1175. if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
  1176. if (S == Case) {
  1177. FoundCase = true;
  1178. return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
  1179. ResultStmts);
  1180. }
  1181. // Otherwise, this is some other case or default statement, just ignore it.
  1182. return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
  1183. ResultStmts);
  1184. }
  1185. // If we are in the live part of the code and we found our break statement,
  1186. // return a success!
  1187. if (!Case && isa<BreakStmt>(S))
  1188. return CSFC_Success;
  1189. // If this is a switch statement, then it might contain the SwitchCase, the
  1190. // break, or neither.
  1191. if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
  1192. // Handle this as two cases: we might be looking for the SwitchCase (if so
  1193. // the skipped statements must be skippable) or we might already have it.
  1194. CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
  1195. bool StartedInLiveCode = FoundCase;
  1196. unsigned StartSize = ResultStmts.size();
  1197. // If we've not found the case yet, scan through looking for it.
  1198. if (Case) {
  1199. // Keep track of whether we see a skipped declaration. The code could be
  1200. // using the declaration even if it is skipped, so we can't optimize out
  1201. // the decl if the kept statements might refer to it.
  1202. bool HadSkippedDecl = false;
  1203. // If we're looking for the case, just see if we can skip each of the
  1204. // substatements.
  1205. for (; Case && I != E; ++I) {
  1206. HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
  1207. switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
  1208. case CSFC_Failure: return CSFC_Failure;
  1209. case CSFC_Success:
  1210. // A successful result means that either 1) that the statement doesn't
  1211. // have the case and is skippable, or 2) does contain the case value
  1212. // and also contains the break to exit the switch. In the later case,
  1213. // we just verify the rest of the statements are elidable.
  1214. if (FoundCase) {
  1215. // If we found the case and skipped declarations, we can't do the
  1216. // optimization.
  1217. if (HadSkippedDecl)
  1218. return CSFC_Failure;
  1219. for (++I; I != E; ++I)
  1220. if (CodeGenFunction::ContainsLabel(*I, true))
  1221. return CSFC_Failure;
  1222. return CSFC_Success;
  1223. }
  1224. break;
  1225. case CSFC_FallThrough:
  1226. // If we have a fallthrough condition, then we must have found the
  1227. // case started to include statements. Consider the rest of the
  1228. // statements in the compound statement as candidates for inclusion.
  1229. assert(FoundCase && "Didn't find case but returned fallthrough?");
  1230. // We recursively found Case, so we're not looking for it anymore.
  1231. Case = nullptr;
  1232. // If we found the case and skipped declarations, we can't do the
  1233. // optimization.
  1234. if (HadSkippedDecl)
  1235. return CSFC_Failure;
  1236. break;
  1237. }
  1238. }
  1239. if (!FoundCase)
  1240. return CSFC_Success;
  1241. assert(!HadSkippedDecl && "fallthrough after skipping decl");
  1242. }
  1243. // If we have statements in our range, then we know that the statements are
  1244. // live and need to be added to the set of statements we're tracking.
  1245. bool AnyDecls = false;
  1246. for (; I != E; ++I) {
  1247. AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
  1248. switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
  1249. case CSFC_Failure: return CSFC_Failure;
  1250. case CSFC_FallThrough:
  1251. // A fallthrough result means that the statement was simple and just
  1252. // included in ResultStmt, keep adding them afterwards.
  1253. break;
  1254. case CSFC_Success:
  1255. // A successful result means that we found the break statement and
  1256. // stopped statement inclusion. We just ensure that any leftover stmts
  1257. // are skippable and return success ourselves.
  1258. for (++I; I != E; ++I)
  1259. if (CodeGenFunction::ContainsLabel(*I, true))
  1260. return CSFC_Failure;
  1261. return CSFC_Success;
  1262. }
  1263. }
  1264. // If we're about to fall out of a scope without hitting a 'break;', we
  1265. // can't perform the optimization if there were any decls in that scope
  1266. // (we'd lose their end-of-lifetime).
  1267. if (AnyDecls) {
  1268. // If the entire compound statement was live, there's one more thing we
  1269. // can try before giving up: emit the whole thing as a single statement.
  1270. // We can do that unless the statement contains a 'break;'.
  1271. // FIXME: Such a break must be at the end of a construct within this one.
  1272. // We could emit this by just ignoring the BreakStmts entirely.
  1273. if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
  1274. ResultStmts.resize(StartSize);
  1275. ResultStmts.push_back(S);
  1276. } else {
  1277. return CSFC_Failure;
  1278. }
  1279. }
  1280. return CSFC_FallThrough;
  1281. }
  1282. // Okay, this is some other statement that we don't handle explicitly, like a
  1283. // for statement or increment etc. If we are skipping over this statement,
  1284. // just verify it doesn't have labels, which would make it invalid to elide.
  1285. if (Case) {
  1286. if (CodeGenFunction::ContainsLabel(S, true))
  1287. return CSFC_Failure;
  1288. return CSFC_Success;
  1289. }
  1290. // Otherwise, we want to include this statement. Everything is cool with that
  1291. // so long as it doesn't contain a break out of the switch we're in.
  1292. if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
  1293. // Otherwise, everything is great. Include the statement and tell the caller
  1294. // that we fall through and include the next statement as well.
  1295. ResultStmts.push_back(S);
  1296. return CSFC_FallThrough;
  1297. }
  1298. /// FindCaseStatementsForValue - Find the case statement being jumped to and
  1299. /// then invoke CollectStatementsForCase to find the list of statements to emit
  1300. /// for a switch on constant. See the comment above CollectStatementsForCase
  1301. /// for more details.
  1302. static bool FindCaseStatementsForValue(const SwitchStmt &S,
  1303. const llvm::APSInt &ConstantCondValue,
  1304. SmallVectorImpl<const Stmt*> &ResultStmts,
  1305. ASTContext &C,
  1306. const SwitchCase *&ResultCase) {
  1307. // First step, find the switch case that is being branched to. We can do this
  1308. // efficiently by scanning the SwitchCase list.
  1309. const SwitchCase *Case = S.getSwitchCaseList();
  1310. const DefaultStmt *DefaultCase = nullptr;
  1311. for (; Case; Case = Case->getNextSwitchCase()) {
  1312. // It's either a default or case. Just remember the default statement in
  1313. // case we're not jumping to any numbered cases.
  1314. if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
  1315. DefaultCase = DS;
  1316. continue;
  1317. }
  1318. // Check to see if this case is the one we're looking for.
  1319. const CaseStmt *CS = cast<CaseStmt>(Case);
  1320. // Don't handle case ranges yet.
  1321. if (CS->getRHS()) return false;
  1322. // If we found our case, remember it as 'case'.
  1323. if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
  1324. break;
  1325. }
  1326. // If we didn't find a matching case, we use a default if it exists, or we
  1327. // elide the whole switch body!
  1328. if (!Case) {
  1329. // It is safe to elide the body of the switch if it doesn't contain labels
  1330. // etc. If it is safe, return successfully with an empty ResultStmts list.
  1331. if (!DefaultCase)
  1332. return !CodeGenFunction::ContainsLabel(&S);
  1333. Case = DefaultCase;
  1334. }
  1335. // Ok, we know which case is being jumped to, try to collect all the
  1336. // statements that follow it. This can fail for a variety of reasons. Also,
  1337. // check to see that the recursive walk actually found our case statement.
  1338. // Insane cases like this can fail to find it in the recursive walk since we
  1339. // don't handle every stmt kind:
  1340. // switch (4) {
  1341. // while (1) {
  1342. // case 4: ...
  1343. bool FoundCase = false;
  1344. ResultCase = Case;
  1345. return CollectStatementsForCase(S.getBody(), Case, FoundCase,
  1346. ResultStmts) != CSFC_Failure &&
  1347. FoundCase;
  1348. }
  1349. void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
  1350. // Handle nested switch statements.
  1351. llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
  1352. SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
  1353. llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
  1354. // See if we can constant fold the condition of the switch and therefore only
  1355. // emit the live case statement (if any) of the switch.
  1356. llvm::APSInt ConstantCondValue;
  1357. if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
  1358. SmallVector<const Stmt*, 4> CaseStmts;
  1359. const SwitchCase *Case = nullptr;
  1360. if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
  1361. getContext(), Case)) {
  1362. if (Case)
  1363. incrementProfileCounter(Case);
  1364. RunCleanupsScope ExecutedScope(*this);
  1365. if (S.getInit())
  1366. EmitStmt(S.getInit());
  1367. // Emit the condition variable if needed inside the entire cleanup scope
  1368. // used by this special case for constant folded switches.
  1369. if (S.getConditionVariable())
  1370. EmitDecl(*S.getConditionVariable());
  1371. // At this point, we are no longer "within" a switch instance, so
  1372. // we can temporarily enforce this to ensure that any embedded case
  1373. // statements are not emitted.
  1374. SwitchInsn = nullptr;
  1375. // Okay, we can dead code eliminate everything except this case. Emit the
  1376. // specified series of statements and we're good.
  1377. for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
  1378. EmitStmt(CaseStmts[i]);
  1379. incrementProfileCounter(&S);
  1380. // Now we want to restore the saved switch instance so that nested
  1381. // switches continue to function properly
  1382. SwitchInsn = SavedSwitchInsn;
  1383. return;
  1384. }
  1385. }
  1386. JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
  1387. RunCleanupsScope ConditionScope(*this);
  1388. if (S.getInit())
  1389. EmitStmt(S.getInit());
  1390. if (S.getConditionVariable())
  1391. EmitDecl(*S.getConditionVariable());
  1392. llvm::Value *CondV = EmitScalarExpr(S.getCond());
  1393. // Create basic block to hold stuff that comes after switch
  1394. // statement. We also need to create a default block now so that
  1395. // explicit case ranges tests can have a place to jump to on
  1396. // failure.
  1397. llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
  1398. SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
  1399. if (PGO.haveRegionCounts()) {
  1400. // Walk the SwitchCase list to find how many there are.
  1401. uint64_t DefaultCount = 0;
  1402. unsigned NumCases = 0;
  1403. for (const SwitchCase *Case = S.getSwitchCaseList();
  1404. Case;
  1405. Case = Case->getNextSwitchCase()) {
  1406. if (isa<DefaultStmt>(Case))
  1407. DefaultCount = getProfileCount(Case);
  1408. NumCases += 1;
  1409. }
  1410. SwitchWeights = new SmallVector<uint64_t, 16>();
  1411. SwitchWeights->reserve(NumCases);
  1412. // The default needs to be first. We store the edge count, so we already
  1413. // know the right weight.
  1414. SwitchWeights->push_back(DefaultCount);
  1415. }
  1416. CaseRangeBlock = DefaultBlock;
  1417. // Clear the insertion point to indicate we are in unreachable code.
  1418. Builder.ClearInsertionPoint();
  1419. // All break statements jump to NextBlock. If BreakContinueStack is non-empty
  1420. // then reuse last ContinueBlock.
  1421. JumpDest OuterContinue;
  1422. if (!BreakContinueStack.empty())
  1423. OuterContinue = BreakContinueStack.back().ContinueBlock;
  1424. BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
  1425. // Emit switch body.
  1426. EmitStmt(S.getBody());
  1427. BreakContinueStack.pop_back();
  1428. // Update the default block in case explicit case range tests have
  1429. // been chained on top.
  1430. SwitchInsn->setDefaultDest(CaseRangeBlock);
  1431. // If a default was never emitted:
  1432. if (!DefaultBlock->getParent()) {
  1433. // If we have cleanups, emit the default block so that there's a
  1434. // place to jump through the cleanups from.
  1435. if (ConditionScope.requiresCleanups()) {
  1436. EmitBlock(DefaultBlock);
  1437. // Otherwise, just forward the default block to the switch end.
  1438. } else {
  1439. DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
  1440. delete DefaultBlock;
  1441. }
  1442. }
  1443. ConditionScope.ForceCleanup();
  1444. // Emit continuation.
  1445. EmitBlock(SwitchExit.getBlock(), true);
  1446. incrementProfileCounter(&S);
  1447. // If the switch has a condition wrapped by __builtin_unpredictable,
  1448. // create metadata that specifies that the switch is unpredictable.
  1449. // Don't bother if not optimizing because that metadata would not be used.
  1450. auto *Call = dyn_cast<CallExpr>(S.getCond());
  1451. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1452. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1453. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1454. llvm::MDBuilder MDHelper(getLLVMContext());
  1455. SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
  1456. MDHelper.createUnpredictable());
  1457. }
  1458. }
  1459. if (SwitchWeights) {
  1460. assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
  1461. "switch weights do not match switch cases");
  1462. // If there's only one jump destination there's no sense weighting it.
  1463. if (SwitchWeights->size() > 1)
  1464. SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
  1465. createProfileWeights(*SwitchWeights));
  1466. delete SwitchWeights;
  1467. }
  1468. SwitchInsn = SavedSwitchInsn;
  1469. SwitchWeights = SavedSwitchWeights;
  1470. CaseRangeBlock = SavedCRBlock;
  1471. }
  1472. static std::string
  1473. SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
  1474. SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
  1475. std::string Result;
  1476. while (*Constraint) {
  1477. switch (*Constraint) {
  1478. default:
  1479. Result += Target.convertConstraint(Constraint);
  1480. break;
  1481. // Ignore these
  1482. case '*':
  1483. case '?':
  1484. case '!':
  1485. case '=': // Will see this and the following in mult-alt constraints.
  1486. case '+':
  1487. break;
  1488. case '#': // Ignore the rest of the constraint alternative.
  1489. while (Constraint[1] && Constraint[1] != ',')
  1490. Constraint++;
  1491. break;
  1492. case '&':
  1493. case '%':
  1494. Result += *Constraint;
  1495. while (Constraint[1] && Constraint[1] == *Constraint)
  1496. Constraint++;
  1497. break;
  1498. case ',':
  1499. Result += "|";
  1500. break;
  1501. case 'g':
  1502. Result += "imr";
  1503. break;
  1504. case '[': {
  1505. assert(OutCons &&
  1506. "Must pass output names to constraints with a symbolic name");
  1507. unsigned Index;
  1508. bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
  1509. assert(result && "Could not resolve symbolic name"); (void)result;
  1510. Result += llvm::utostr(Index);
  1511. break;
  1512. }
  1513. }
  1514. Constraint++;
  1515. }
  1516. return Result;
  1517. }
  1518. /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
  1519. /// as using a particular register add that as a constraint that will be used
  1520. /// in this asm stmt.
  1521. static std::string
  1522. AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
  1523. const TargetInfo &Target, CodeGenModule &CGM,
  1524. const AsmStmt &Stmt, const bool EarlyClobber) {
  1525. const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
  1526. if (!AsmDeclRef)
  1527. return Constraint;
  1528. const ValueDecl &Value = *AsmDeclRef->getDecl();
  1529. const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
  1530. if (!Variable)
  1531. return Constraint;
  1532. if (Variable->getStorageClass() != SC_Register)
  1533. return Constraint;
  1534. AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
  1535. if (!Attr)
  1536. return Constraint;
  1537. StringRef Register = Attr->getLabel();
  1538. assert(Target.isValidGCCRegisterName(Register));
  1539. // We're using validateOutputConstraint here because we only care if
  1540. // this is a register constraint.
  1541. TargetInfo::ConstraintInfo Info(Constraint, "");
  1542. if (Target.validateOutputConstraint(Info) &&
  1543. !Info.allowsRegister()) {
  1544. CGM.ErrorUnsupported(&Stmt, "__asm__");
  1545. return Constraint;
  1546. }
  1547. // Canonicalize the register here before returning it.
  1548. Register = Target.getNormalizedGCCRegisterName(Register);
  1549. return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
  1550. }
  1551. llvm::Value*
  1552. CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  1553. LValue InputValue, QualType InputType,
  1554. std::string &ConstraintStr,
  1555. SourceLocation Loc) {
  1556. llvm::Value *Arg;
  1557. if (Info.allowsRegister() || !Info.allowsMemory()) {
  1558. if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
  1559. Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
  1560. } else {
  1561. llvm::Type *Ty = ConvertType(InputType);
  1562. uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
  1563. if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
  1564. Ty = llvm::IntegerType::get(getLLVMContext(), Size);
  1565. Ty = llvm::PointerType::getUnqual(Ty);
  1566. Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
  1567. Ty));
  1568. } else {
  1569. Arg = InputValue.getPointer();
  1570. ConstraintStr += '*';
  1571. }
  1572. }
  1573. } else {
  1574. Arg = InputValue.getPointer();
  1575. ConstraintStr += '*';
  1576. }
  1577. return Arg;
  1578. }
  1579. llvm::Value* CodeGenFunction::EmitAsmInput(
  1580. const TargetInfo::ConstraintInfo &Info,
  1581. const Expr *InputExpr,
  1582. std::string &ConstraintStr) {
  1583. // If this can't be a register or memory, i.e., has to be a constant
  1584. // (immediate or symbolic), try to emit it as such.
  1585. if (!Info.allowsRegister() && !Info.allowsMemory()) {
  1586. if (Info.requiresImmediateConstant()) {
  1587. Expr::EvalResult EVResult;
  1588. InputExpr->EvaluateAsRValue(EVResult, getContext(), true);
  1589. llvm::APSInt IntResult;
  1590. if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
  1591. getContext()))
  1592. return llvm::ConstantInt::get(getLLVMContext(), IntResult);
  1593. }
  1594. Expr::EvalResult Result;
  1595. if (InputExpr->EvaluateAsInt(Result, getContext()))
  1596. return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt());
  1597. }
  1598. if (Info.allowsRegister() || !Info.allowsMemory())
  1599. if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
  1600. return EmitScalarExpr(InputExpr);
  1601. if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
  1602. return EmitScalarExpr(InputExpr);
  1603. InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
  1604. LValue Dest = EmitLValue(InputExpr);
  1605. return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
  1606. InputExpr->getExprLoc());
  1607. }
  1608. /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
  1609. /// asm call instruction. The !srcloc MDNode contains a list of constant
  1610. /// integers which are the source locations of the start of each line in the
  1611. /// asm.
  1612. static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
  1613. CodeGenFunction &CGF) {
  1614. SmallVector<llvm::Metadata *, 8> Locs;
  1615. // Add the location of the first line to the MDNode.
  1616. Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  1617. CGF.Int32Ty, Str->getBeginLoc().getRawEncoding())));
  1618. StringRef StrVal = Str->getString();
  1619. if (!StrVal.empty()) {
  1620. const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
  1621. const LangOptions &LangOpts = CGF.CGM.getLangOpts();
  1622. unsigned StartToken = 0;
  1623. unsigned ByteOffset = 0;
  1624. // Add the location of the start of each subsequent line of the asm to the
  1625. // MDNode.
  1626. for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
  1627. if (StrVal[i] != '\n') continue;
  1628. SourceLocation LineLoc = Str->getLocationOfByte(
  1629. i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
  1630. Locs.push_back(llvm::ConstantAsMetadata::get(
  1631. llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
  1632. }
  1633. }
  1634. return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
  1635. }
  1636. static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
  1637. bool ReadOnly, bool ReadNone, const AsmStmt &S,
  1638. const std::vector<llvm::Type *> &ResultRegTypes,
  1639. CodeGenFunction &CGF,
  1640. std::vector<llvm::Value *> &RegResults) {
  1641. Result.addAttribute(llvm::AttributeList::FunctionIndex,
  1642. llvm::Attribute::NoUnwind);
  1643. // Attach readnone and readonly attributes.
  1644. if (!HasSideEffect) {
  1645. if (ReadNone)
  1646. Result.addAttribute(llvm::AttributeList::FunctionIndex,
  1647. llvm::Attribute::ReadNone);
  1648. else if (ReadOnly)
  1649. Result.addAttribute(llvm::AttributeList::FunctionIndex,
  1650. llvm::Attribute::ReadOnly);
  1651. }
  1652. // Slap the source location of the inline asm into a !srcloc metadata on the
  1653. // call.
  1654. if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
  1655. Result.setMetadata("srcloc",
  1656. getAsmSrcLocInfo(gccAsmStmt->getAsmString(), CGF));
  1657. else {
  1658. // At least put the line number on MS inline asm blobs.
  1659. llvm::Constant *Loc = llvm::ConstantInt::get(CGF.Int32Ty,
  1660. S.getAsmLoc().getRawEncoding());
  1661. Result.setMetadata("srcloc",
  1662. llvm::MDNode::get(CGF.getLLVMContext(),
  1663. llvm::ConstantAsMetadata::get(Loc)));
  1664. }
  1665. if (CGF.getLangOpts().assumeFunctionsAreConvergent())
  1666. // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
  1667. // convergent (meaning, they may call an intrinsically convergent op, such
  1668. // as bar.sync, and so can't have certain optimizations applied around
  1669. // them).
  1670. Result.addAttribute(llvm::AttributeList::FunctionIndex,
  1671. llvm::Attribute::Convergent);
  1672. // Extract all of the register value results from the asm.
  1673. if (ResultRegTypes.size() == 1) {
  1674. RegResults.push_back(&Result);
  1675. } else {
  1676. for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
  1677. llvm::Value *Tmp = CGF.Builder.CreateExtractValue(&Result, i, "asmresult");
  1678. RegResults.push_back(Tmp);
  1679. }
  1680. }
  1681. }
  1682. void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
  1683. // Assemble the final asm string.
  1684. std::string AsmString = S.generateAsmString(getContext());
  1685. // Get all the output and input constraints together.
  1686. SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
  1687. SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
  1688. for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
  1689. StringRef Name;
  1690. if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
  1691. Name = GAS->getOutputName(i);
  1692. TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
  1693. bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
  1694. assert(IsValid && "Failed to parse output constraint");
  1695. OutputConstraintInfos.push_back(Info);
  1696. }
  1697. for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
  1698. StringRef Name;
  1699. if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
  1700. Name = GAS->getInputName(i);
  1701. TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
  1702. bool IsValid =
  1703. getTarget().validateInputConstraint(OutputConstraintInfos, Info);
  1704. assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
  1705. InputConstraintInfos.push_back(Info);
  1706. }
  1707. std::string Constraints;
  1708. std::vector<LValue> ResultRegDests;
  1709. std::vector<QualType> ResultRegQualTys;
  1710. std::vector<llvm::Type *> ResultRegTypes;
  1711. std::vector<llvm::Type *> ResultTruncRegTypes;
  1712. std::vector<llvm::Type *> ArgTypes;
  1713. std::vector<llvm::Value*> Args;
  1714. // Keep track of inout constraints.
  1715. std::string InOutConstraints;
  1716. std::vector<llvm::Value*> InOutArgs;
  1717. std::vector<llvm::Type*> InOutArgTypes;
  1718. // Keep track of out constraints for tied input operand.
  1719. std::vector<std::string> OutputConstraints;
  1720. // An inline asm can be marked readonly if it meets the following conditions:
  1721. // - it doesn't have any sideeffects
  1722. // - it doesn't clobber memory
  1723. // - it doesn't return a value by-reference
  1724. // It can be marked readnone if it doesn't have any input memory constraints
  1725. // in addition to meeting the conditions listed above.
  1726. bool ReadOnly = true, ReadNone = true;
  1727. for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
  1728. TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
  1729. // Simplify the output constraint.
  1730. std::string OutputConstraint(S.getOutputConstraint(i));
  1731. OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
  1732. getTarget(), &OutputConstraintInfos);
  1733. const Expr *OutExpr = S.getOutputExpr(i);
  1734. OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
  1735. OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
  1736. getTarget(), CGM, S,
  1737. Info.earlyClobber());
  1738. OutputConstraints.push_back(OutputConstraint);
  1739. LValue Dest = EmitLValue(OutExpr);
  1740. if (!Constraints.empty())
  1741. Constraints += ',';
  1742. // If this is a register output, then make the inline asm return it
  1743. // by-value. If this is a memory result, return the value by-reference.
  1744. if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
  1745. Constraints += "=" + OutputConstraint;
  1746. ResultRegQualTys.push_back(OutExpr->getType());
  1747. ResultRegDests.push_back(Dest);
  1748. ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
  1749. ResultTruncRegTypes.push_back(ResultRegTypes.back());
  1750. // If this output is tied to an input, and if the input is larger, then
  1751. // we need to set the actual result type of the inline asm node to be the
  1752. // same as the input type.
  1753. if (Info.hasMatchingInput()) {
  1754. unsigned InputNo;
  1755. for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
  1756. TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
  1757. if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
  1758. break;
  1759. }
  1760. assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
  1761. QualType InputTy = S.getInputExpr(InputNo)->getType();
  1762. QualType OutputType = OutExpr->getType();
  1763. uint64_t InputSize = getContext().getTypeSize(InputTy);
  1764. if (getContext().getTypeSize(OutputType) < InputSize) {
  1765. // Form the asm to return the value as a larger integer or fp type.
  1766. ResultRegTypes.back() = ConvertType(InputTy);
  1767. }
  1768. }
  1769. if (llvm::Type* AdjTy =
  1770. getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
  1771. ResultRegTypes.back()))
  1772. ResultRegTypes.back() = AdjTy;
  1773. else {
  1774. CGM.getDiags().Report(S.getAsmLoc(),
  1775. diag::err_asm_invalid_type_in_input)
  1776. << OutExpr->getType() << OutputConstraint;
  1777. }
  1778. // Update largest vector width for any vector types.
  1779. if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
  1780. LargestVectorWidth = std::max(LargestVectorWidth,
  1781. VT->getPrimitiveSizeInBits());
  1782. } else {
  1783. ArgTypes.push_back(Dest.getAddress().getType());
  1784. Args.push_back(Dest.getPointer());
  1785. Constraints += "=*";
  1786. Constraints += OutputConstraint;
  1787. ReadOnly = ReadNone = false;
  1788. }
  1789. if (Info.isReadWrite()) {
  1790. InOutConstraints += ',';
  1791. const Expr *InputExpr = S.getOutputExpr(i);
  1792. llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
  1793. InOutConstraints,
  1794. InputExpr->getExprLoc());
  1795. if (llvm::Type* AdjTy =
  1796. getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
  1797. Arg->getType()))
  1798. Arg = Builder.CreateBitCast(Arg, AdjTy);
  1799. // Update largest vector width for any vector types.
  1800. if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
  1801. LargestVectorWidth = std::max(LargestVectorWidth,
  1802. VT->getPrimitiveSizeInBits());
  1803. if (Info.allowsRegister())
  1804. InOutConstraints += llvm::utostr(i);
  1805. else
  1806. InOutConstraints += OutputConstraint;
  1807. InOutArgTypes.push_back(Arg->getType());
  1808. InOutArgs.push_back(Arg);
  1809. }
  1810. }
  1811. // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
  1812. // to the return value slot. Only do this when returning in registers.
  1813. if (isa<MSAsmStmt>(&S)) {
  1814. const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
  1815. if (RetAI.isDirect() || RetAI.isExtend()) {
  1816. // Make a fake lvalue for the return value slot.
  1817. LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
  1818. CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
  1819. *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
  1820. ResultRegDests, AsmString, S.getNumOutputs());
  1821. SawAsmBlock = true;
  1822. }
  1823. }
  1824. for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
  1825. const Expr *InputExpr = S.getInputExpr(i);
  1826. TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
  1827. if (Info.allowsMemory())
  1828. ReadNone = false;
  1829. if (!Constraints.empty())
  1830. Constraints += ',';
  1831. // Simplify the input constraint.
  1832. std::string InputConstraint(S.getInputConstraint(i));
  1833. InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
  1834. &OutputConstraintInfos);
  1835. InputConstraint = AddVariableConstraints(
  1836. InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
  1837. getTarget(), CGM, S, false /* No EarlyClobber */);
  1838. std::string ReplaceConstraint (InputConstraint);
  1839. llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
  1840. // If this input argument is tied to a larger output result, extend the
  1841. // input to be the same size as the output. The LLVM backend wants to see
  1842. // the input and output of a matching constraint be the same size. Note
  1843. // that GCC does not define what the top bits are here. We use zext because
  1844. // that is usually cheaper, but LLVM IR should really get an anyext someday.
  1845. if (Info.hasTiedOperand()) {
  1846. unsigned Output = Info.getTiedOperand();
  1847. QualType OutputType = S.getOutputExpr(Output)->getType();
  1848. QualType InputTy = InputExpr->getType();
  1849. if (getContext().getTypeSize(OutputType) >
  1850. getContext().getTypeSize(InputTy)) {
  1851. // Use ptrtoint as appropriate so that we can do our extension.
  1852. if (isa<llvm::PointerType>(Arg->getType()))
  1853. Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
  1854. llvm::Type *OutputTy = ConvertType(OutputType);
  1855. if (isa<llvm::IntegerType>(OutputTy))
  1856. Arg = Builder.CreateZExt(Arg, OutputTy);
  1857. else if (isa<llvm::PointerType>(OutputTy))
  1858. Arg = Builder.CreateZExt(Arg, IntPtrTy);
  1859. else {
  1860. assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
  1861. Arg = Builder.CreateFPExt(Arg, OutputTy);
  1862. }
  1863. }
  1864. // Deal with the tied operands' constraint code in adjustInlineAsmType.
  1865. ReplaceConstraint = OutputConstraints[Output];
  1866. }
  1867. if (llvm::Type* AdjTy =
  1868. getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint,
  1869. Arg->getType()))
  1870. Arg = Builder.CreateBitCast(Arg, AdjTy);
  1871. else
  1872. CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
  1873. << InputExpr->getType() << InputConstraint;
  1874. // Update largest vector width for any vector types.
  1875. if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
  1876. LargestVectorWidth = std::max(LargestVectorWidth,
  1877. VT->getPrimitiveSizeInBits());
  1878. ArgTypes.push_back(Arg->getType());
  1879. Args.push_back(Arg);
  1880. Constraints += InputConstraint;
  1881. }
  1882. // Append the "input" part of inout constraints last.
  1883. for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
  1884. ArgTypes.push_back(InOutArgTypes[i]);
  1885. Args.push_back(InOutArgs[i]);
  1886. }
  1887. Constraints += InOutConstraints;
  1888. // Labels
  1889. SmallVector<llvm::BasicBlock *, 16> Transfer;
  1890. llvm::BasicBlock *Fallthrough = nullptr;
  1891. bool IsGCCAsmGoto = false;
  1892. if (const auto *GS = dyn_cast<GCCAsmStmt>(&S)) {
  1893. IsGCCAsmGoto = GS->isAsmGoto();
  1894. if (IsGCCAsmGoto) {
  1895. for (auto *E : GS->labels()) {
  1896. JumpDest Dest = getJumpDestForLabel(E->getLabel());
  1897. Transfer.push_back(Dest.getBlock());
  1898. llvm::BlockAddress *BA =
  1899. llvm::BlockAddress::get(CurFn, Dest.getBlock());
  1900. Args.push_back(BA);
  1901. ArgTypes.push_back(BA->getType());
  1902. if (!Constraints.empty())
  1903. Constraints += ',';
  1904. Constraints += 'X';
  1905. }
  1906. StringRef Name = "asm.fallthrough";
  1907. Fallthrough = createBasicBlock(Name);
  1908. }
  1909. }
  1910. // Clobbers
  1911. for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
  1912. StringRef Clobber = S.getClobber(i);
  1913. if (Clobber == "memory")
  1914. ReadOnly = ReadNone = false;
  1915. else if (Clobber != "cc")
  1916. Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
  1917. if (!Constraints.empty())
  1918. Constraints += ',';
  1919. Constraints += "~{";
  1920. Constraints += Clobber;
  1921. Constraints += '}';
  1922. }
  1923. // Add machine specific clobbers
  1924. std::string MachineClobbers = getTarget().getClobbers();
  1925. if (!MachineClobbers.empty()) {
  1926. if (!Constraints.empty())
  1927. Constraints += ',';
  1928. Constraints += MachineClobbers;
  1929. }
  1930. llvm::Type *ResultType;
  1931. if (ResultRegTypes.empty())
  1932. ResultType = VoidTy;
  1933. else if (ResultRegTypes.size() == 1)
  1934. ResultType = ResultRegTypes[0];
  1935. else
  1936. ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
  1937. llvm::FunctionType *FTy =
  1938. llvm::FunctionType::get(ResultType, ArgTypes, false);
  1939. bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
  1940. llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
  1941. llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
  1942. llvm::InlineAsm *IA =
  1943. llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
  1944. /* IsAlignStack */ false, AsmDialect);
  1945. std::vector<llvm::Value*> RegResults;
  1946. if (IsGCCAsmGoto) {
  1947. llvm::CallBrInst *Result =
  1948. Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
  1949. UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly,
  1950. ReadNone, S, ResultRegTypes, *this, RegResults);
  1951. EmitBlock(Fallthrough);
  1952. } else {
  1953. llvm::CallInst *Result =
  1954. Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
  1955. UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly,
  1956. ReadNone, S, ResultRegTypes, *this, RegResults);
  1957. }
  1958. assert(RegResults.size() == ResultRegTypes.size());
  1959. assert(RegResults.size() == ResultTruncRegTypes.size());
  1960. assert(RegResults.size() == ResultRegDests.size());
  1961. for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
  1962. llvm::Value *Tmp = RegResults[i];
  1963. // If the result type of the LLVM IR asm doesn't match the result type of
  1964. // the expression, do the conversion.
  1965. if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
  1966. llvm::Type *TruncTy = ResultTruncRegTypes[i];
  1967. // Truncate the integer result to the right size, note that TruncTy can be
  1968. // a pointer.
  1969. if (TruncTy->isFloatingPointTy())
  1970. Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
  1971. else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
  1972. uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
  1973. Tmp = Builder.CreateTrunc(Tmp,
  1974. llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
  1975. Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
  1976. } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
  1977. uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
  1978. Tmp = Builder.CreatePtrToInt(Tmp,
  1979. llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
  1980. Tmp = Builder.CreateTrunc(Tmp, TruncTy);
  1981. } else if (TruncTy->isIntegerTy()) {
  1982. Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
  1983. } else if (TruncTy->isVectorTy()) {
  1984. Tmp = Builder.CreateBitCast(Tmp, TruncTy);
  1985. }
  1986. }
  1987. EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
  1988. }
  1989. }
  1990. LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
  1991. const RecordDecl *RD = S.getCapturedRecordDecl();
  1992. QualType RecordTy = getContext().getRecordType(RD);
  1993. // Initialize the captured struct.
  1994. LValue SlotLV =
  1995. MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
  1996. RecordDecl::field_iterator CurField = RD->field_begin();
  1997. for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
  1998. E = S.capture_init_end();
  1999. I != E; ++I, ++CurField) {
  2000. LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
  2001. if (CurField->hasCapturedVLAType()) {
  2002. auto VAT = CurField->getCapturedVLAType();
  2003. EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
  2004. } else {
  2005. EmitInitializerForField(*CurField, LV, *I);
  2006. }
  2007. }
  2008. return SlotLV;
  2009. }
  2010. /// Generate an outlined function for the body of a CapturedStmt, store any
  2011. /// captured variables into the captured struct, and call the outlined function.
  2012. llvm::Function *
  2013. CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
  2014. LValue CapStruct = InitCapturedStruct(S);
  2015. // Emit the CapturedDecl
  2016. CodeGenFunction CGF(CGM, true);
  2017. CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
  2018. llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
  2019. delete CGF.CapturedStmtInfo;
  2020. // Emit call to the helper function.
  2021. EmitCallOrInvoke(F, CapStruct.getPointer());
  2022. return F;
  2023. }
  2024. Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
  2025. LValue CapStruct = InitCapturedStruct(S);
  2026. return CapStruct.getAddress();
  2027. }
  2028. /// Creates the outlined function for a CapturedStmt.
  2029. llvm::Function *
  2030. CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
  2031. assert(CapturedStmtInfo &&
  2032. "CapturedStmtInfo should be set when generating the captured function");
  2033. const CapturedDecl *CD = S.getCapturedDecl();
  2034. const RecordDecl *RD = S.getCapturedRecordDecl();
  2035. SourceLocation Loc = S.getBeginLoc();
  2036. assert(CD->hasBody() && "missing CapturedDecl body");
  2037. // Build the argument list.
  2038. ASTContext &Ctx = CGM.getContext();
  2039. FunctionArgList Args;
  2040. Args.append(CD->param_begin(), CD->param_end());
  2041. // Create the function declaration.
  2042. const CGFunctionInfo &FuncInfo =
  2043. CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
  2044. llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
  2045. llvm::Function *F =
  2046. llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
  2047. CapturedStmtInfo->getHelperName(), &CGM.getModule());
  2048. CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
  2049. if (CD->isNothrow())
  2050. F->addFnAttr(llvm::Attribute::NoUnwind);
  2051. // Generate the function.
  2052. StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
  2053. CD->getBody()->getBeginLoc());
  2054. // Set the context parameter in CapturedStmtInfo.
  2055. Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
  2056. CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
  2057. // Initialize variable-length arrays.
  2058. LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
  2059. Ctx.getTagDeclType(RD));
  2060. for (auto *FD : RD->fields()) {
  2061. if (FD->hasCapturedVLAType()) {
  2062. auto *ExprArg =
  2063. EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc())
  2064. .getScalarVal();
  2065. auto VAT = FD->getCapturedVLAType();
  2066. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  2067. }
  2068. }
  2069. // If 'this' is captured, load it into CXXThisValue.
  2070. if (CapturedStmtInfo->isCXXThisExprCaptured()) {
  2071. FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
  2072. LValue ThisLValue = EmitLValueForField(Base, FD);
  2073. CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
  2074. }
  2075. PGO.assignRegionCounters(GlobalDecl(CD), F);
  2076. CapturedStmtInfo->EmitBody(*this, CD->getBody());
  2077. FinishFunction(CD->getBodyRBrace());
  2078. return F;
  2079. }