CGStmt.cpp 91 KB

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