MMRScriptCollector.cs 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  28. using System;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Reflection.Emit;
  33. using System.Text;
  34. /**
  35. * @brief Wrapper class for ScriptMyILGen to do simple optimizations.
  36. * The main one is to figure out which locals are active at the labels
  37. * so the stack capture/restore code doesn't have to do everything.
  38. * Second is it removes unnecessary back-to-back stloc/ldloc's.
  39. */
  40. namespace OpenSim.Region.ScriptEngine.Yengine
  41. {
  42. /**
  43. * @brief This is a list that keeps track of types pushed on the evaluation stack.
  44. */
  45. public class StackDepth: List<Type>
  46. {
  47. public List<bool> isBoxeds = new List<bool>();
  48. /**
  49. * @brief Clear both stacks.
  50. */
  51. public new void Clear()
  52. {
  53. base.Clear();
  54. isBoxeds.Clear();
  55. }
  56. /**
  57. * @brief Pop call parameters and validate the types.
  58. */
  59. public void Pop(ParameterInfo[] pis)
  60. {
  61. int n = pis.Length;
  62. int c = this.Count;
  63. if(n > c)
  64. throw new Exception("stack going negative");
  65. for(int i = n; --i >= 0;)
  66. {
  67. --c;
  68. ExpectedVsOnStack(pis[i].ParameterType, this[c], isBoxeds[c]);
  69. }
  70. Pop(n);
  71. }
  72. /**
  73. * @brief Pop values and validate the types.
  74. */
  75. public void Pop(Type[] ts)
  76. {
  77. int n = ts.Length;
  78. int c = this.Count;
  79. if(n > c)
  80. throw new Exception("stack going negative");
  81. for(int i = ts.Length; --i >= 0;)
  82. {
  83. --c;
  84. ExpectedVsOnStack(ts[i], this[c], isBoxeds[c]);
  85. }
  86. Pop(n);
  87. }
  88. /**
  89. * @brief Pop a single value and validate the type.
  90. */
  91. public void Pop(Type t)
  92. {
  93. int c = this.Count;
  94. if(c < 1)
  95. throw new Exception("stack going negative");
  96. ExpectedVsOnStack(t, this[c - 1], isBoxeds[c - 1]);
  97. Pop(1);
  98. }
  99. /**
  100. * @brief Pop a single value and validate that it is a numeric type.
  101. */
  102. public Type PopNumVal()
  103. {
  104. int c = this.Count;
  105. if(c < 1)
  106. throw new Exception("stack going negative");
  107. Type st = this[--c];
  108. if(st == null)
  109. {
  110. throw new Exception("stack has null, expecting a numeric");
  111. }
  112. if(isBoxeds[c])
  113. {
  114. throw new Exception("stack is boxed " + st.Name + ", expecting a numeric");
  115. }
  116. if((st != typeof(bool)) && (st != typeof(char)) && (st != typeof(int)) &&
  117. (st != typeof(long)) && (st != typeof(float)) && (st != typeof(double)))
  118. {
  119. throw new Exception("stack has " + st.Name + ", expecting a numeric");
  120. }
  121. return Pop(1);
  122. }
  123. /**
  124. * @brief Pop a single value and validate that it is a reference type
  125. */
  126. public Type PopRef()
  127. {
  128. int c = this.Count;
  129. if(c < 1)
  130. throw new Exception("stack going negative");
  131. Type st = this[--c];
  132. if((st != null) && !isBoxeds[c] && st.IsValueType)
  133. {
  134. throw new Exception("stack has " + st.Name + ", expecting a ref type");
  135. }
  136. return Pop(1);
  137. }
  138. /**
  139. * @brief Pop a single value and validate that it is a value type
  140. */
  141. public Type PopValue()
  142. {
  143. int c = this.Count;
  144. if(c < 1)
  145. throw new Exception("stack going negative");
  146. Type st = this[--c];
  147. if(st == null)
  148. {
  149. throw new Exception("stack has null, expecting a value type");
  150. }
  151. if(!st.IsValueType)
  152. {
  153. throw new Exception("stack has " + st.Name + ", expecting a value type");
  154. }
  155. if(isBoxeds[c])
  156. {
  157. throw new Exception("stack has boxed " + st.Name + ", expecting an unboxed value type");
  158. }
  159. return Pop(1);
  160. }
  161. // ex = what is expected to be on stack
  162. // st = what is actually on stack (null for ldnull)
  163. // stBoxed = stack value is boxed
  164. public static void ExpectedVsOnStack(Type ex, Type st, bool stBoxed)
  165. {
  166. // ldnull pushed on stack can go into any pointer type
  167. if(st == null)
  168. {
  169. if(ex.IsByRef || ex.IsPointer || ex.IsClass || ex.IsInterface)
  170. return;
  171. throw new Exception("stack has null, expect " + ex.Name);
  172. }
  173. // simple case of expecting an object
  174. // ...so the stack can have object,string, etc
  175. // but we cant allow int = boxed int here
  176. if(ex.IsAssignableFrom(st) && !stBoxed)
  177. return;
  178. // case of expecting an enum on the stack
  179. // but all the CIL code knows about are ints etc
  180. // so convert the Enum type to integer or whatever
  181. // and that should be assignable from what's on stack
  182. if(ex.IsEnum && typeof(int).IsAssignableFrom(st))
  183. return;
  184. // bool, char, int are interchangeable on the stack
  185. if((ex == typeof(bool) || ex == typeof(char) || ex == typeof(int)) &&
  186. (st == typeof(bool) || st == typeof(char) || st == typeof(int)))
  187. return;
  188. // float and double are interchangeable on the stack
  189. if((ex == typeof(float) || ex == typeof(double)) &&
  190. (st == typeof(float) || st == typeof(double)))
  191. return;
  192. // object can accept any boxed type
  193. if((ex == typeof(object)) && stBoxed)
  194. return;
  195. // otherwise, it is disallowed
  196. throw new Exception("stack has " + StackTypeString(st, stBoxed) + ", expect " + ex.Name);
  197. }
  198. /**
  199. * @brief Pop values without any validation.
  200. */
  201. public Type Pop(int n)
  202. {
  203. if(this.Count != isBoxeds.Count)
  204. throw new Exception("isBoxeds count bad");
  205. Type lastPopped = null;
  206. int c = this.Count;
  207. if(n > c)
  208. throw new Exception("stack going negative");
  209. if(n > 0)
  210. {
  211. lastPopped = this[c - n];
  212. this.RemoveRange(c - n, n);
  213. isBoxeds.RemoveRange(c - n, n);
  214. }
  215. if(this.Count != isBoxeds.Count)
  216. throw new Exception("isBoxeds count bad");
  217. return lastPopped;
  218. }
  219. /**
  220. * @brief Peek at the n'th stack value.
  221. * n = 0 : top of stack
  222. * 1 : next to top
  223. * ...
  224. */
  225. public Type Peek(int n)
  226. {
  227. int c = this.Count;
  228. if(n > c - 1)
  229. throw new Exception("stack going negative");
  230. if(this.Count != isBoxeds.Count)
  231. throw new Exception("isBoxeds count bad");
  232. return this[c - n - 1];
  233. }
  234. public bool PeekBoxed(int n)
  235. {
  236. int c = isBoxeds.Count;
  237. if(n > c - 1)
  238. throw new Exception("stack going negative");
  239. if(this.Count != isBoxeds.Count)
  240. throw new Exception("isBoxeds count bad");
  241. return isBoxeds[c - n - 1];
  242. }
  243. /**
  244. * @brief Push a single value of the given type.
  245. */
  246. public void Push(Type t)
  247. {
  248. Push(t, false);
  249. }
  250. public void Push(Type t, bool isBoxed)
  251. {
  252. if(this.Count != isBoxeds.Count)
  253. throw new Exception("isBoxeds count bad");
  254. this.Add(t);
  255. isBoxeds.Add(isBoxed);
  256. }
  257. /**
  258. * @brief See if the types at a given label exactly match those on the stack.
  259. * We should have the stack types be the same no matter how we branched
  260. * or fell through to a particular label.
  261. */
  262. public void Matches(ScriptMyLabel label)
  263. {
  264. Type[] ts = label.stackDepth;
  265. bool[] tsBoxeds = label.stackBoxeds;
  266. int i;
  267. if(this.Count != isBoxeds.Count)
  268. throw new Exception("isBoxeds count bad");
  269. if(ts == null)
  270. {
  271. label.stackDepth = this.ToArray();
  272. label.stackBoxeds = isBoxeds.ToArray();
  273. }
  274. else if(ts.Length != this.Count)
  275. {
  276. throw new Exception("stack depth mismatch");
  277. }
  278. else
  279. {
  280. for(i = this.Count; --i >= 0;)
  281. {
  282. if(tsBoxeds[i] != this.isBoxeds[i])
  283. goto mismatch;
  284. if(ts[i] == this[i])
  285. continue;
  286. if((ts[i] == typeof(bool) || ts[i] == typeof(char) || ts[i] == typeof(int)) &&
  287. (this[i] == typeof(bool) || this[i] == typeof(char) || this[i] == typeof(int)))
  288. continue;
  289. if((ts[i] == typeof(double) || ts[i] == typeof(float)) &&
  290. (this[i] == typeof(double) || this[i] == typeof(float)))
  291. continue;
  292. goto mismatch;
  293. }
  294. }
  295. return;
  296. mismatch:
  297. throw new Exception("stack type mismatch: " + StackTypeString(ts[i], tsBoxeds[i]) + " vs " + StackTypeString(this[i], this.isBoxeds[i]));
  298. }
  299. private static string StackTypeString(Type ts, bool isBoxed)
  300. {
  301. if(!isBoxed)
  302. return ts.Name;
  303. return "[" + ts.Name + "]";
  304. }
  305. }
  306. /**
  307. * @brief One of these per opcode and label in the function plus other misc markers.
  308. * They form the CIL instruction stream of the function.
  309. */
  310. public abstract class GraphNode
  311. {
  312. private static readonly bool DEBUG = false;
  313. public const int OPINDENT = 4;
  314. public const int OPDEBLEN = 12;
  315. public ScriptCollector coll;
  316. public GraphNodeBeginExceptionBlock tryBlock; // start of enclosing try block
  317. // valid in the try section
  318. // null in the catch/finally sections
  319. // null outside of try block
  320. // for the try node itself, links to outer try block
  321. public GraphNodeBeginExceptionBlock excBlock; // start of enclosing try block
  322. // valid in the try/catch/finally sections
  323. // null outside of try/catch/finally block
  324. // for the try node itself, links to outer try block
  325. /*
  326. * List of nodes in order as originally given.
  327. */
  328. public GraphNode nextLin, prevLin;
  329. public int linSeqNo;
  330. /**
  331. * @brief Save pointer to collector.
  332. */
  333. public GraphNode(ScriptCollector coll)
  334. {
  335. this.coll = coll;
  336. }
  337. /**
  338. * @brief Chain graph node to end of linear list.
  339. */
  340. public virtual void ChainLin()
  341. {
  342. coll.lastLin.nextLin = this;
  343. this.prevLin = coll.lastLin;
  344. coll.lastLin = this;
  345. this.tryBlock = coll.curTryBlock;
  346. this.excBlock = coll.curExcBlock;
  347. if(DEBUG)
  348. {
  349. StringBuilder sb = new StringBuilder("ChainLin*:");
  350. sb.Append(coll.stackDepth.Count.ToString("D2"));
  351. sb.Append(' ');
  352. this.DebString(sb);
  353. Console.WriteLine(sb.ToString());
  354. }
  355. }
  356. /**
  357. * @brief Append full info to debugging string for printing out the instruction.
  358. */
  359. public void DebStringExt(StringBuilder sb)
  360. {
  361. int x = sb.Length;
  362. sb.Append(this.linSeqNo.ToString().PadLeft(5));
  363. sb.Append(": ");
  364. this.DebString(sb);
  365. if(this.ReadsLocal() != null)
  366. ScriptCollector.PadToLength(sb, x + 60, " [read]");
  367. if(this.WritesLocal() != null)
  368. ScriptCollector.PadToLength(sb, x + 68, " [write]");
  369. ScriptCollector.PadToLength(sb, x + 72, " ->");
  370. bool first = true;
  371. foreach(GraphNode nn in this.NextNodes)
  372. {
  373. if(first)
  374. {
  375. sb.Append(nn.linSeqNo.ToString().PadLeft(5));
  376. first = false;
  377. }
  378. else
  379. {
  380. sb.Append(',');
  381. sb.Append(nn.linSeqNo);
  382. }
  383. }
  384. }
  385. /**
  386. * @brief See if it's possible for it to fall through to the next inline (nextLin) instruction.
  387. */
  388. public virtual bool CanFallThrough()
  389. {
  390. return true;
  391. }
  392. /**
  393. * @brief Append to debugging string for printing out the instruction.
  394. */
  395. public abstract void DebString(StringBuilder sb);
  396. public override string ToString()
  397. {
  398. StringBuilder sb = new StringBuilder();
  399. this.DebString(sb);
  400. return sb.ToString();
  401. }
  402. /**
  403. * @brief See if this instruction reads a local variable.
  404. */
  405. public virtual ScriptMyLocal ReadsLocal()
  406. {
  407. return null;
  408. }
  409. /**
  410. * @brief See if this instruction writes a local variable.
  411. */
  412. public virtual ScriptMyLocal WritesLocal()
  413. {
  414. return null;
  415. }
  416. /**
  417. * @brief Write this instruction out to the wrapped object file.
  418. */
  419. public abstract void WriteOutOne(ScriptMyILGen ilGen);
  420. /**
  421. * @brief Iterate through all the possible next nodes, including the next inline node, if any.
  422. * The next inline code is excluded if the instruction never falls through, eg, return, unconditional branch.
  423. * It includes a possible conditional branch to the beginning of the corresponding catch/finally of every
  424. * instruction in a try section.
  425. */
  426. private System.Collections.Generic.IEnumerable<GraphNode> nextNodes, nextNodesCatchFinally;
  427. public System.Collections.Generic.IEnumerable<GraphNode> NextNodes
  428. {
  429. get
  430. {
  431. if(nextNodes == null)
  432. {
  433. nextNodes = GetNNEnumerable();
  434. nextNodesCatchFinally = new NNEnumerableCatchFinally(this);
  435. }
  436. return nextNodesCatchFinally;
  437. }
  438. }
  439. /**
  440. * @brief This acts as a wrapper around all the other NNEnumerable's below.
  441. * It assumes every instruction in a try { } can throw an exception so it
  442. * says that every instruction in a try { } can conditionally branch to
  443. * the beginning of the corresponding catch { } or finally { }.
  444. */
  445. private class NNEnumerableCatchFinally: System.Collections.Generic.IEnumerable<GraphNode>
  446. {
  447. private GraphNode gn;
  448. public NNEnumerableCatchFinally(GraphNode gn)
  449. {
  450. this.gn = gn;
  451. }
  452. System.Collections.Generic.IEnumerator<GraphNode> System.Collections.Generic.IEnumerable<GraphNode>.GetEnumerator()
  453. {
  454. return new NNEnumeratorCatchFinally(gn);
  455. }
  456. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  457. {
  458. return new NNEnumeratorCatchFinally(gn);
  459. }
  460. }
  461. private class NNEnumeratorCatchFinally: NNEnumeratorBase
  462. {
  463. private GraphNode gn;
  464. private int index = 0;
  465. private System.Collections.Generic.IEnumerator<GraphNode> realEnumerator;
  466. public NNEnumeratorCatchFinally(GraphNode gn)
  467. {
  468. this.gn = gn;
  469. this.realEnumerator = gn.nextNodes.GetEnumerator();
  470. }
  471. public override bool MoveNext()
  472. {
  473. // First off, return any targets the instruction can come up with.
  474. if(realEnumerator.MoveNext())
  475. {
  476. nn = realEnumerator.Current;
  477. return true;
  478. }
  479. // Then if this instruction is in a try section, say this instruction
  480. // can potentially branch to the beginning of the corresponding
  481. // catch/finally.
  482. if((index == 0) && (gn.tryBlock != null))
  483. {
  484. index++;
  485. nn = gn.tryBlock.catchFinallyBlock;
  486. return true;
  487. }
  488. // That's all we can do.
  489. nn = null;
  490. return false;
  491. }
  492. public override void Reset()
  493. {
  494. realEnumerator.Reset();
  495. index = 0;
  496. nn = null;
  497. }
  498. }
  499. /**
  500. * @brief This default iterator always returns the next inline node as the one-and-only next node.
  501. * Other instructions need to override it if they can possibly do other than that.
  502. */
  503. /**
  504. * @brief GetNNEnumerable() gets the nextnode enumerable part of a GraphNode,
  505. * which in turn gives the list of nodes that can possibly be next in
  506. * a flow-control sense. It simply instantiates the NNEnumerator sub-
  507. * class which does the actual enumeration.
  508. */
  509. protected virtual System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
  510. {
  511. return new NNEnumerable(this, typeof(NNEnumerator));
  512. }
  513. private class NNEnumerator: NNEnumeratorBase
  514. {
  515. private GraphNode gn;
  516. private int index;
  517. public NNEnumerator(GraphNode gn)
  518. {
  519. this.gn = gn;
  520. }
  521. public override bool MoveNext()
  522. {
  523. switch(index)
  524. {
  525. case 0:
  526. {
  527. index++;
  528. nn = gn.nextLin;
  529. return nn != null;
  530. }
  531. case 1:
  532. {
  533. nn = null;
  534. return false;
  535. }
  536. }
  537. throw new Exception();
  538. }
  539. public override void Reset()
  540. {
  541. index = 0;
  542. nn = null;
  543. }
  544. }
  545. }
  546. /**
  547. * @brief Things that derive from this are the beginning of a block.
  548. * A block of code is that which begins with a label or is the beginning of all code
  549. * and it contains no labels, ie, it can't be jumped into other than at its beginning.
  550. */
  551. public abstract class GraphNodeBlock: GraphNode
  552. {
  553. public List<ScriptMyLocal> localsWrittenBeforeRead = new List<ScriptMyLocal>();
  554. public List<ScriptMyLocal> localsReadBeforeWritten = new List<ScriptMyLocal>();
  555. public int hasBeenResolved;
  556. public GraphNodeBlock(ScriptCollector coll) : base(coll) { }
  557. }
  558. /**
  559. * @brief This placeholder is at the beginning of the code so the first few instructions
  560. * belong to some block.
  561. */
  562. public class GraphNodeBegin: GraphNodeBlock
  563. {
  564. public GraphNodeBegin(ScriptCollector coll) : base(coll) { }
  565. public override void DebString(StringBuilder sb)
  566. {
  567. sb.Append("begin");
  568. }
  569. public override void WriteOutOne(ScriptMyILGen ilGen)
  570. {
  571. }
  572. }
  573. /**
  574. * @brief Beginning of try block.
  575. */
  576. public class GraphNodeBeginExceptionBlock: GraphNodeBlock
  577. {
  578. public GraphNodeBeginExceptionBlock outerTryBlock; // next outer try opcode or null
  579. public GraphNodeCatchFinallyBlock catchFinallyBlock; // start of associated catch or finally
  580. public GraphNodeEndExceptionBlock endExcBlock; // end of associated catch or finally
  581. public int excBlkSeqNo; // debugging
  582. public GraphNodeBeginExceptionBlock(ScriptCollector coll) : base(coll)
  583. {
  584. }
  585. public override void ChainLin()
  586. {
  587. base.ChainLin();
  588. // we should always start try blocks with nothing on stack
  589. // ...as CLI wipes stack for various conditions
  590. if(coll.stackDepth.Count != 0)
  591. {
  592. throw new Exception("stack depth " + coll.stackDepth.Count);
  593. }
  594. }
  595. public override void DebString(StringBuilder sb)
  596. {
  597. sb.Append(" beginexceptionblock_");
  598. sb.Append(excBlkSeqNo);
  599. }
  600. public override void WriteOutOne(ScriptMyILGen ilGen)
  601. {
  602. ilGen.BeginExceptionBlock();
  603. }
  604. }
  605. /**
  606. * @brief Beginning of catch or finally block.
  607. */
  608. public abstract class GraphNodeCatchFinallyBlock: GraphNodeBlock
  609. {
  610. public GraphNodeCatchFinallyBlock(ScriptCollector coll) : base(coll)
  611. {
  612. }
  613. public override void ChainLin()
  614. {
  615. base.ChainLin();
  616. // we should always start catch/finally blocks with nothing on stack
  617. // ...as CLI wipes stack for various conditions
  618. if(coll.stackDepth.Count != 0)
  619. {
  620. throw new Exception("stack depth " + coll.stackDepth.Count);
  621. }
  622. }
  623. }
  624. /**
  625. * @brief Beginning of catch block.
  626. */
  627. public class GraphNodeBeginCatchBlock: GraphNodeCatchFinallyBlock
  628. {
  629. public Type excType;
  630. public GraphNodeBeginCatchBlock(ScriptCollector coll, Type excType) : base(coll)
  631. {
  632. this.excType = excType;
  633. }
  634. public override void ChainLin()
  635. {
  636. base.ChainLin();
  637. // catch block always enters with one value on stack
  638. if(coll.stackDepth.Count != 0)
  639. {
  640. throw new Exception("stack depth " + coll.stackDepth.Count);
  641. }
  642. coll.stackDepth.Push(excType);
  643. }
  644. public override void DebString(StringBuilder sb)
  645. {
  646. sb.Append(" begincatchblock_");
  647. sb.Append(excBlock.excBlkSeqNo);
  648. }
  649. public override void WriteOutOne(ScriptMyILGen ilGen)
  650. {
  651. ilGen.BeginCatchBlock(excType);
  652. }
  653. /**
  654. * @brief The beginning of every catch { } conditinally branches to the beginning
  655. * of all outer catch { }s up to and including the next outer finally { }.
  656. */
  657. protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
  658. {
  659. return new NNEnumerable(this, typeof(NNEnumerator));
  660. }
  661. private class NNEnumerator: NNEnumeratorBase
  662. {
  663. private GraphNodeBeginCatchBlock gn;
  664. private int index;
  665. public NNEnumerator(GraphNodeBeginCatchBlock gn)
  666. {
  667. this.gn = gn;
  668. }
  669. public override bool MoveNext()
  670. {
  671. while(true)
  672. {
  673. switch(index)
  674. {
  675. case 0:
  676. {
  677. // start with the fallthru
  678. nn = gn.nextLin;
  679. index++;
  680. return true;
  681. }
  682. case 1:
  683. {
  684. // get the first outer catch { } or finally { }
  685. // pretend we last returned beginning of this catch { }
  686. // then loop back to get next outer catch { } or finally { }
  687. nn = gn;
  688. break;
  689. }
  690. case 2:
  691. {
  692. // nn points to a catch { } previously returned
  693. // get the corresponding try { }
  694. GraphNodeBeginExceptionBlock nntry = nn.excBlock;
  695. // step out to next outer try { }
  696. nntry = nntry.excBlock;
  697. if(nntry == null)
  698. break;
  699. // return corresponding catch { } or finally { }
  700. nn = nntry.catchFinallyBlock;
  701. // if it's a finally { } we don't do anything after that
  702. if(nn is GraphNodeBeginFinallyBlock)
  703. index++;
  704. return true;
  705. }
  706. case 3:
  707. {
  708. // we've returned the fallthru, catches and one finally
  709. // so there's nothing more to say
  710. nn = null;
  711. return false;
  712. }
  713. default:
  714. throw new Exception();
  715. }
  716. index++;
  717. }
  718. }
  719. public override void Reset()
  720. {
  721. index = 0;
  722. nn = null;
  723. }
  724. }
  725. }
  726. /**
  727. * @brief Beginning of finally block.
  728. */
  729. public class GraphNodeBeginFinallyBlock: GraphNodeCatchFinallyBlock
  730. {
  731. // leaveTargets has a list of all the targets of any contained
  732. // leave instructions, ie, where an endfinally can possibly jump.
  733. // But only those targets within the next outer finally { }, we
  734. // don't contain any targets outside of that, those targets are
  735. // stored in the actual finally that will jump to the target.
  736. // The endfinally enumerator assumes that it is always possible
  737. // for it to jump to the next outer finally (as would happen for
  738. // an uncaught exception), so no need to do anything special.
  739. public List<GraphNodeBlock> leaveTargets = new List<GraphNodeBlock>();
  740. public GraphNodeBeginFinallyBlock(ScriptCollector coll) : base(coll)
  741. {
  742. }
  743. public override void DebString(StringBuilder sb)
  744. {
  745. sb.Append(" beginfinallyblock_");
  746. sb.Append(excBlock.excBlkSeqNo);
  747. }
  748. public override void WriteOutOne(ScriptMyILGen ilGen)
  749. {
  750. ilGen.BeginFinallyBlock();
  751. }
  752. }
  753. /**
  754. * @brief End of try/catch/finally block.
  755. */
  756. public class GraphNodeEndExceptionBlock: GraphNode
  757. {
  758. public GraphNodeEndExceptionBlock(ScriptCollector coll) : base(coll)
  759. {
  760. }
  761. public override void ChainLin()
  762. {
  763. base.ChainLin();
  764. // we should always end exception blocks with nothing on stack
  765. // ...as CLI wipes stack for various conditions
  766. if(coll.stackDepth.Count != 0)
  767. {
  768. throw new Exception("stack depth " + coll.stackDepth.Count);
  769. }
  770. }
  771. public override void DebString(StringBuilder sb)
  772. {
  773. sb.Append(" endexceptionblock_");
  774. sb.Append(excBlock.excBlkSeqNo);
  775. }
  776. public override void WriteOutOne(ScriptMyILGen ilGen)
  777. {
  778. ilGen.EndExceptionBlock();
  779. }
  780. }
  781. /**
  782. * @brief Actual instruction emits...
  783. */
  784. public abstract class GraphNodeEmit: GraphNode
  785. {
  786. public OpCode opcode;
  787. public Token errorAt;
  788. public GraphNodeEmit(ScriptCollector coll, Token errorAt, OpCode opcode) : base(coll)
  789. {
  790. this.opcode = opcode;
  791. this.errorAt = errorAt;
  792. }
  793. public override void ChainLin()
  794. {
  795. base.ChainLin();
  796. // compute resultant stack depth
  797. int stack = coll.stackDepth.Count;
  798. if((stack != 0) && ((opcode == OpCodes.Endfinally) || (opcode == OpCodes.Leave) || (opcode == OpCodes.Rethrow)))
  799. {
  800. throw new Exception(opcode + " stack depth " + stack);
  801. }
  802. if((stack != 1) && (opcode == OpCodes.Throw))
  803. {
  804. throw new Exception(opcode + " stack depth " + stack);
  805. }
  806. }
  807. /**
  808. * @brief See if it's possible for it to fall through to the next inline (nextLin) instruction.
  809. */
  810. public override bool CanFallThrough()
  811. {
  812. switch(opcode.FlowControl)
  813. {
  814. case FlowControl.Branch:
  815. return false; // unconditional branch
  816. case FlowControl.Break:
  817. return true; // break
  818. case FlowControl.Call:
  819. return true; // call
  820. case FlowControl.Cond_Branch:
  821. return true; // conditional branch
  822. case FlowControl.Next:
  823. return true; // falls through to next instruction
  824. case FlowControl.Return:
  825. return false; // return
  826. case FlowControl.Throw:
  827. return false; // throw
  828. default:
  829. {
  830. string op = opcode.ToString();
  831. if(op == "volatile.")
  832. return true;
  833. throw new Exception("unknown flow control " + opcode.FlowControl + " for " + op);
  834. }
  835. }
  836. }
  837. // if followed by OpCodes.Pop, it can be discarded
  838. public bool isPoppable
  839. {
  840. get
  841. {
  842. return
  843. ((opcode.StackBehaviourPop == StackBehaviour.Pop0) && // ldarg,ldloc,ldsfld
  844. (opcode.StackBehaviourPush == StackBehaviour.Push1)) ||
  845. ((opcode.StackBehaviourPop == StackBehaviour.Pop0) && // ldarga,ldloca,ldc,ldsflda,...
  846. (opcode.StackBehaviourPush == StackBehaviour.Pushi)) ||
  847. (opcode == OpCodes.Ldnull) ||
  848. (opcode == OpCodes.Ldc_R4) ||
  849. (opcode == OpCodes.Ldc_R8) ||
  850. (opcode == OpCodes.Ldstr) ||
  851. (opcode == OpCodes.Ldc_I8) ||
  852. (opcode == OpCodes.Dup);
  853. }
  854. }
  855. public override void DebString(StringBuilder sb)
  856. {
  857. sb.Append("".PadRight(OPINDENT));
  858. sb.Append(opcode.ToString().PadRight(OPDEBLEN));
  859. }
  860. /**
  861. * @brief If instruction is terminating, we say there is nothing following (eg, return).
  862. * Otherwise, say the one-and-only next instruction is the next instruction inline.
  863. */
  864. protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
  865. {
  866. return new NNEnumerable(this, typeof(NNEnumerator));
  867. }
  868. private class NNEnumerator: NNEnumeratorBase
  869. {
  870. private GraphNodeEmit gn;
  871. private int index;
  872. public NNEnumerator(GraphNodeEmit gn)
  873. {
  874. this.gn = gn;
  875. }
  876. public override bool MoveNext()
  877. {
  878. switch(index)
  879. {
  880. case 0:
  881. {
  882. if(gn.CanFallThrough())
  883. {
  884. index++;
  885. nn = gn.nextLin;
  886. return nn != null;
  887. }
  888. return false;
  889. }
  890. case 1:
  891. {
  892. nn = null;
  893. return false;
  894. }
  895. }
  896. throw new Exception();
  897. }
  898. public override void Reset()
  899. {
  900. index = 0;
  901. nn = null;
  902. }
  903. }
  904. }
  905. public class GraphNodeEmitNull: GraphNodeEmit
  906. {
  907. public GraphNodeEmitNull(ScriptCollector coll, Token errorAt, OpCode opcode) : base(coll, errorAt, opcode)
  908. {
  909. }
  910. public override void ChainLin()
  911. {
  912. base.ChainLin();
  913. switch(opcode.ToString())
  914. {
  915. case "nop":
  916. break;
  917. case "break":
  918. break;
  919. case "volatile.":
  920. break;
  921. case "ldarg.0":
  922. coll.stackDepth.Push(coll.wrapped.argTypes[0]);
  923. break;
  924. case "ldarg.1":
  925. coll.stackDepth.Push(coll.wrapped.argTypes[1]);
  926. break;
  927. case "ldarg.2":
  928. coll.stackDepth.Push(coll.wrapped.argTypes[2]);
  929. break;
  930. case "ldarg.3":
  931. coll.stackDepth.Push(coll.wrapped.argTypes[3]);
  932. break;
  933. case "ldnull":
  934. coll.stackDepth.Push(null);
  935. break;
  936. case "ldc.i4.m1":
  937. case "ldc.i4.0":
  938. case "ldc.i4.1":
  939. case "ldc.i4.2":
  940. case "ldc.i4.3":
  941. case "ldc.i4.4":
  942. case "ldc.i4.5":
  943. case "ldc.i4.6":
  944. case "ldc.i4.7":
  945. case "ldc.i4.8":
  946. {
  947. coll.stackDepth.Push(typeof(int));
  948. break;
  949. }
  950. case "dup":
  951. {
  952. Type t = coll.stackDepth.Peek(0);
  953. bool b = coll.stackDepth.PeekBoxed(0);
  954. coll.stackDepth.Push(t, b);
  955. break;
  956. }
  957. case "pop":
  958. {
  959. coll.stackDepth.Pop(1);
  960. break;
  961. }
  962. case "ret":
  963. {
  964. int sd = (coll.wrapped.retType != typeof(void)) ? 1 : 0;
  965. if(coll.stackDepth.Count != sd)
  966. throw new Exception("bad stack depth");
  967. if(sd > 0)
  968. {
  969. coll.stackDepth.Pop(coll.wrapped.retType);
  970. }
  971. break;
  972. }
  973. case "add":
  974. case "sub":
  975. case "mul":
  976. case "div":
  977. case "div.un":
  978. case "rem":
  979. case "rem.un":
  980. case "and":
  981. case "or":
  982. case "xor":
  983. case "shl":
  984. case "shr":
  985. case "shr.un":
  986. case "add.ovf":
  987. case "add.ovf.un":
  988. case "mul.ovf":
  989. case "mul.ovf.un":
  990. case "sub.ovf":
  991. case "sub.ovf.un":
  992. {
  993. coll.stackDepth.PopNumVal();
  994. Type t = coll.stackDepth.PopNumVal();
  995. coll.stackDepth.Push(t);
  996. break;
  997. }
  998. case "neg":
  999. case "not":
  1000. {
  1001. Type t = coll.stackDepth.PopNumVal();
  1002. coll.stackDepth.Push(t);
  1003. break;
  1004. }
  1005. case "conv.i1":
  1006. case "conv.i2":
  1007. case "conv.i4":
  1008. case "conv.i8":
  1009. case "conv.r4":
  1010. case "conv.r8":
  1011. case "conv.u4":
  1012. case "conv.u8":
  1013. case "conv.r.un":
  1014. case "conv.ovf.i1.un":
  1015. case "conv.ovf.i2.un":
  1016. case "conv.ovf.i4.un":
  1017. case "conv.ovf.i8.un":
  1018. case "conv.ovf.u1.un":
  1019. case "conv.ovf.u2.un":
  1020. case "conv.ovf.u4.un":
  1021. case "conv.ovf.u8.un":
  1022. case "conv.ovf.i.un":
  1023. case "conv.ovf.u.un":
  1024. case "conv.ovf.i1":
  1025. case "conv.ovf.u1":
  1026. case "conv.ovf.i2":
  1027. case "conv.ovf.u2":
  1028. case "conv.ovf.i4":
  1029. case "conv.ovf.u4":
  1030. case "conv.ovf.i8":
  1031. case "conv.ovf.u8":
  1032. case "conv.u2":
  1033. case "conv.u1":
  1034. case "conv.i":
  1035. case "conv.ovf.i":
  1036. case "conv.ovf.u":
  1037. case "conv.u":
  1038. {
  1039. coll.stackDepth.PopNumVal();
  1040. coll.stackDepth.Push(ConvToType(opcode));
  1041. break;
  1042. }
  1043. case "throw":
  1044. {
  1045. if(coll.stackDepth.Count != 1)
  1046. throw new Exception("bad stack depth " + coll.stackDepth.Count);
  1047. coll.stackDepth.PopRef();
  1048. break;
  1049. }
  1050. case "ldlen":
  1051. {
  1052. coll.stackDepth.Pop(typeof(string));
  1053. coll.stackDepth.Push(typeof(int));
  1054. break;
  1055. }
  1056. case "ldelem.i1":
  1057. case "ldelem.u1":
  1058. case "ldelem.i2":
  1059. case "ldelem.u2":
  1060. case "ldelem.i4":
  1061. case "ldelem.u4":
  1062. case "ldelem.i8":
  1063. case "ldelem.i":
  1064. case "ldelem.r4":
  1065. case "ldelem.r8":
  1066. case "ldelem.ref":
  1067. {
  1068. Type t = coll.stackDepth.Peek(1).GetElementType();
  1069. coll.stackDepth.Pop(typeof(int));
  1070. coll.stackDepth.Pop(t.MakeArrayType());
  1071. coll.stackDepth.Push(t);
  1072. break;
  1073. }
  1074. case "stelem.i":
  1075. case "stelem.i1":
  1076. case "stelem.i2":
  1077. case "stelem.i4":
  1078. case "stelem.i8":
  1079. case "stelem.r4":
  1080. case "stelem.r8":
  1081. case "stelem.ref":
  1082. {
  1083. Type t = coll.stackDepth.Peek(2).GetElementType();
  1084. coll.stackDepth.Pop(t);
  1085. coll.stackDepth.Pop(typeof(int));
  1086. coll.stackDepth.Pop(t.MakeArrayType());
  1087. break;
  1088. }
  1089. case "endfinally":
  1090. case "rethrow":
  1091. {
  1092. if(coll.stackDepth.Count != 0)
  1093. throw new Exception("bad stack depth " + coll.stackDepth.Count);
  1094. break;
  1095. }
  1096. case "ceq":
  1097. {
  1098. Type t = coll.stackDepth.Pop(1);
  1099. if(t == null)
  1100. {
  1101. coll.stackDepth.PopRef();
  1102. }
  1103. else
  1104. {
  1105. coll.stackDepth.Pop(t);
  1106. }
  1107. coll.stackDepth.Push(typeof(int));
  1108. break;
  1109. }
  1110. case "cgt":
  1111. case "cgt.un":
  1112. case "clt":
  1113. case "clt.un":
  1114. {
  1115. coll.stackDepth.PopNumVal();
  1116. coll.stackDepth.PopNumVal();
  1117. coll.stackDepth.Push(typeof(int));
  1118. break;
  1119. }
  1120. case "ldind.i4":
  1121. {
  1122. coll.stackDepth.Pop(typeof(int).MakeByRefType());
  1123. coll.stackDepth.Push(typeof(int));
  1124. break;
  1125. }
  1126. case "stind.i4":
  1127. {
  1128. coll.stackDepth.Pop(typeof(int));
  1129. coll.stackDepth.Pop(typeof(int).MakeByRefType());
  1130. break;
  1131. }
  1132. default:
  1133. throw new Exception("unknown opcode " + opcode.ToString());
  1134. }
  1135. }
  1136. private static Type ConvToType(OpCode opcode)
  1137. {
  1138. string s = opcode.ToString();
  1139. s = s.Substring(5); // strip off "conv."
  1140. if(s.StartsWith("ovf."))
  1141. s = s.Substring(4);
  1142. if(s.EndsWith(".un"))
  1143. s = s.Substring(0, s.Length - 3);
  1144. switch(s)
  1145. {
  1146. case "i":
  1147. return typeof(IntPtr);
  1148. case "i1":
  1149. return typeof(sbyte);
  1150. case "i2":
  1151. return typeof(short);
  1152. case "i4":
  1153. return typeof(int);
  1154. case "i8":
  1155. return typeof(long);
  1156. case "r":
  1157. case "r4":
  1158. return typeof(float);
  1159. case "r8":
  1160. return typeof(double);
  1161. case "u1":
  1162. return typeof(byte);
  1163. case "u2":
  1164. return typeof(ushort);
  1165. case "u4":
  1166. return typeof(uint);
  1167. case "u8":
  1168. return typeof(ulong);
  1169. case "u":
  1170. return typeof(UIntPtr);
  1171. default:
  1172. throw new Exception("unknown opcode " + opcode.ToString());
  1173. }
  1174. }
  1175. public override void WriteOutOne(ScriptMyILGen ilGen)
  1176. {
  1177. ilGen.Emit(errorAt, opcode);
  1178. }
  1179. }
  1180. public class GraphNodeEmitNullEndfinally: GraphNodeEmitNull
  1181. {
  1182. public GraphNodeEmitNullEndfinally(ScriptCollector coll, Token errorAt) : base(coll, errorAt, OpCodes.Endfinally)
  1183. {
  1184. }
  1185. /**
  1186. * @brief Endfinally can branch to:
  1187. * 1) the corresponding EndExceptionBlock
  1188. * 2) any of the corresponding BeginFinallyBlock's leaveTargets
  1189. * 3) the next outer BeginFinallyBlock
  1190. */
  1191. protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
  1192. {
  1193. return new NNEnumerable(this, typeof(NNEnumerator));
  1194. }
  1195. private class NNEnumerator: NNEnumeratorBase
  1196. {
  1197. private GraphNodeEmitNullEndfinally gn;
  1198. private IEnumerator<GraphNodeBlock> leaveTargetEnumerator;
  1199. private int index;
  1200. public NNEnumerator(GraphNodeEmitNullEndfinally gn)
  1201. {
  1202. this.gn = gn;
  1203. // endfinally instruction must be within some try/catch/finally mess
  1204. GraphNodeBeginExceptionBlock thistry = gn.excBlock;
  1205. // endfinally instruction must be within some finally { } mess
  1206. GraphNodeBeginFinallyBlock thisfin = (GraphNodeBeginFinallyBlock)thistry.catchFinallyBlock;
  1207. // get the list of the finally { } leave instruction targets
  1208. this.leaveTargetEnumerator = thisfin.leaveTargets.GetEnumerator();
  1209. }
  1210. public override bool MoveNext()
  1211. {
  1212. while(true)
  1213. {
  1214. switch(index)
  1215. {
  1216. // to start, return end of our finally { }
  1217. case 0:
  1218. {
  1219. GraphNodeBeginExceptionBlock thistry = gn.excBlock;
  1220. nn = thistry.endExcBlock;
  1221. if(nn == null)
  1222. throw new NullReferenceException("thistry.endExcBlock");
  1223. index++;
  1224. return true;
  1225. }
  1226. // return next one of our finally { }'s leave targets
  1227. // ie, where any leave instructions in the try { } want
  1228. // the finally { } to go to when it finishes
  1229. case 1:
  1230. {
  1231. if(this.leaveTargetEnumerator.MoveNext())
  1232. {
  1233. nn = this.leaveTargetEnumerator.Current;
  1234. if(nn == null)
  1235. throw new NullReferenceException("this.leaveTargetEnumerator.Current");
  1236. return true;
  1237. }
  1238. break;
  1239. }
  1240. // return beginning of next outer finally { }
  1241. case 2:
  1242. {
  1243. GraphNodeBeginExceptionBlock nntry = gn.excBlock;
  1244. while((nntry = nntry.excBlock) != null)
  1245. {
  1246. if(nntry.catchFinallyBlock is GraphNodeBeginFinallyBlock)
  1247. {
  1248. nn = nntry.catchFinallyBlock;
  1249. if(nn == null)
  1250. throw new NullReferenceException("nntry.catchFinallyBlock");
  1251. index++;
  1252. return true;
  1253. }
  1254. }
  1255. break;
  1256. }
  1257. // got nothing more
  1258. case 3:
  1259. {
  1260. return false;
  1261. }
  1262. default:
  1263. throw new Exception();
  1264. }
  1265. index++;
  1266. }
  1267. }
  1268. public override void Reset()
  1269. {
  1270. leaveTargetEnumerator.Reset();
  1271. index = 0;
  1272. nn = null;
  1273. }
  1274. }
  1275. }
  1276. public class GraphNodeEmitField: GraphNodeEmit
  1277. {
  1278. public FieldInfo field;
  1279. public GraphNodeEmitField(ScriptCollector coll, Token errorAt, OpCode opcode, FieldInfo field) : base(coll, errorAt, opcode)
  1280. {
  1281. this.field = field;
  1282. }
  1283. public override void ChainLin()
  1284. {
  1285. base.ChainLin();
  1286. switch(opcode.ToString())
  1287. {
  1288. case "ldfld":
  1289. PopPointer();
  1290. coll.stackDepth.Push(field.FieldType);
  1291. break;
  1292. case "ldflda":
  1293. PopPointer();
  1294. coll.stackDepth.Push(field.FieldType.MakeByRefType());
  1295. break;
  1296. case "stfld":
  1297. coll.stackDepth.Pop(field.FieldType);
  1298. PopPointer();
  1299. break;
  1300. case "ldsfld":
  1301. coll.stackDepth.Push(field.FieldType);
  1302. break;
  1303. case "ldsflda":
  1304. coll.stackDepth.Push(field.FieldType.MakeByRefType());
  1305. break;
  1306. case "stsfld":
  1307. coll.stackDepth.Pop(field.FieldType);
  1308. break;
  1309. default:
  1310. throw new Exception("unknown opcode " + opcode.ToString());
  1311. }
  1312. }
  1313. private void PopPointer()
  1314. {
  1315. Type t = field.DeclaringType; // get class/field type
  1316. if(t.IsValueType)
  1317. {
  1318. Type brt = t.MakeByRefType(); // if value type, eg Vector, it can be pushed by reference or by value
  1319. int c = coll.stackDepth.Count;
  1320. if((c > 0) && (coll.stackDepth[c - 1] == brt))
  1321. t = brt;
  1322. }
  1323. coll.stackDepth.Pop(t); // type of what should be on the stack pointing to object or struct
  1324. }
  1325. public override void DebString(StringBuilder sb)
  1326. {
  1327. base.DebString(sb);
  1328. sb.Append(field.Name);
  1329. }
  1330. public override void WriteOutOne(ScriptMyILGen ilGen)
  1331. {
  1332. ilGen.Emit(errorAt, opcode, field);
  1333. }
  1334. }
  1335. public class GraphNodeEmitLocal: GraphNodeEmit
  1336. {
  1337. public ScriptMyLocal myLocal;
  1338. public GraphNodeEmitLocal(ScriptCollector coll, Token errorAt, OpCode opcode, ScriptMyLocal myLocal) : base(coll, errorAt, opcode)
  1339. {
  1340. this.myLocal = myLocal;
  1341. }
  1342. public override void ChainLin()
  1343. {
  1344. base.ChainLin();
  1345. switch(opcode.ToString())
  1346. {
  1347. case "ldloc":
  1348. coll.stackDepth.Push(myLocal.type);
  1349. break;
  1350. case "ldloca":
  1351. coll.stackDepth.Push(myLocal.type.MakeByRefType());
  1352. break;
  1353. case "stloc":
  1354. coll.stackDepth.Pop(myLocal.type);
  1355. break;
  1356. default:
  1357. throw new Exception("unknown opcode " + opcode.ToString());
  1358. }
  1359. }
  1360. public override void DebString(StringBuilder sb)
  1361. {
  1362. base.DebString(sb);
  1363. sb.Append(myLocal.name);
  1364. }
  1365. public override ScriptMyLocal ReadsLocal()
  1366. {
  1367. if(opcode == OpCodes.Ldloc)
  1368. return myLocal;
  1369. if(opcode == OpCodes.Ldloca)
  1370. return myLocal;
  1371. if(opcode == OpCodes.Stloc)
  1372. return null;
  1373. throw new Exception("unknown opcode " + opcode);
  1374. }
  1375. public override ScriptMyLocal WritesLocal()
  1376. {
  1377. if(opcode == OpCodes.Ldloc)
  1378. return null;
  1379. if(opcode == OpCodes.Ldloca)
  1380. return myLocal;
  1381. if(opcode == OpCodes.Stloc)
  1382. return myLocal;
  1383. throw new Exception("unknown opcode " + opcode);
  1384. }
  1385. public override void WriteOutOne(ScriptMyILGen ilGen)
  1386. {
  1387. ilGen.Emit(errorAt, opcode, myLocal);
  1388. }
  1389. }
  1390. public class GraphNodeEmitType: GraphNodeEmit
  1391. {
  1392. public Type type;
  1393. public GraphNodeEmitType(ScriptCollector coll, Token errorAt, OpCode opcode, Type type) : base(coll, errorAt, opcode)
  1394. {
  1395. this.type = type;
  1396. }
  1397. public override void ChainLin()
  1398. {
  1399. base.ChainLin();
  1400. switch(opcode.ToString())
  1401. {
  1402. case "castclass":
  1403. case "isinst":
  1404. {
  1405. coll.stackDepth.PopRef();
  1406. coll.stackDepth.Push(type, type.IsValueType);
  1407. break;
  1408. }
  1409. case "box":
  1410. {
  1411. if(!type.IsValueType)
  1412. throw new Exception("can't box a non-value type");
  1413. coll.stackDepth.Pop(type);
  1414. coll.stackDepth.Push(type, true);
  1415. break;
  1416. }
  1417. case "unbox":
  1418. case "unbox.any":
  1419. {
  1420. if(!type.IsValueType)
  1421. throw new Exception("can't unbox to a non-value type");
  1422. coll.stackDepth.PopRef();
  1423. coll.stackDepth.Push(type);
  1424. break;
  1425. }
  1426. case "newarr":
  1427. {
  1428. coll.stackDepth.Pop(typeof(int));
  1429. coll.stackDepth.Push(type.MakeArrayType());
  1430. break;
  1431. }
  1432. case "sizeof":
  1433. {
  1434. coll.stackDepth.Pop(1);
  1435. coll.stackDepth.Push(typeof(int));
  1436. break;
  1437. }
  1438. case "ldelem":
  1439. {
  1440. coll.stackDepth.Pop(typeof(int));
  1441. coll.stackDepth.Pop(type.MakeArrayType());
  1442. coll.stackDepth.Push(type);
  1443. break;
  1444. }
  1445. case "ldelema":
  1446. {
  1447. coll.stackDepth.Pop(typeof(int));
  1448. coll.stackDepth.Pop(type.MakeArrayType());
  1449. coll.stackDepth.Push(type.MakeByRefType());
  1450. break;
  1451. }
  1452. case "stelem":
  1453. {
  1454. coll.stackDepth.Pop(type);
  1455. coll.stackDepth.Pop(typeof(int));
  1456. coll.stackDepth.Pop(type.MakeArrayType());
  1457. break;
  1458. }
  1459. default:
  1460. throw new Exception("unknown opcode " + opcode.ToString());
  1461. }
  1462. }
  1463. public override void DebString(StringBuilder sb)
  1464. {
  1465. base.DebString(sb);
  1466. sb.Append(type.Name);
  1467. }
  1468. public override void WriteOutOne(ScriptMyILGen ilGen)
  1469. {
  1470. ilGen.Emit(errorAt, opcode, type);
  1471. }
  1472. }
  1473. public class GraphNodeEmitLabel: GraphNodeEmit
  1474. {
  1475. public ScriptMyLabel myLabel;
  1476. public GraphNodeEmitLabel(ScriptCollector coll, Token errorAt, OpCode opcode, ScriptMyLabel myLabel) : base(coll, errorAt, opcode)
  1477. {
  1478. this.myLabel = myLabel;
  1479. }
  1480. public override void ChainLin()
  1481. {
  1482. base.ChainLin();
  1483. switch(opcode.ToString())
  1484. {
  1485. case "brfalse.s":
  1486. case "brtrue.s":
  1487. case "brfalse":
  1488. case "brtrue":
  1489. {
  1490. coll.stackDepth.Pop(1);
  1491. break;
  1492. }
  1493. case "beq.s":
  1494. case "bge.s":
  1495. case "bgt.s":
  1496. case "ble.s":
  1497. case "blt.s":
  1498. case "bne.un.s":
  1499. case "bge.un.s":
  1500. case "bgt.un.s":
  1501. case "ble.un.s":
  1502. case "blt.un.s":
  1503. case "beq":
  1504. case "bge":
  1505. case "bgt":
  1506. case "ble":
  1507. case "blt":
  1508. case "bne.un":
  1509. case "bge.un":
  1510. case "bgt.un":
  1511. case "ble.un":
  1512. case "blt.un":
  1513. {
  1514. coll.stackDepth.PopNumVal();
  1515. coll.stackDepth.PopNumVal();
  1516. break;
  1517. }
  1518. case "br":
  1519. case "br.s":
  1520. break;
  1521. case "leave":
  1522. {
  1523. if(coll.stackDepth.Count != 0)
  1524. throw new Exception("bad stack depth " + coll.stackDepth.Count);
  1525. break;
  1526. }
  1527. default:
  1528. throw new Exception("unknown opcode " + opcode.ToString());
  1529. }
  1530. // if a target doesn't have a depth yet, set its depth to the depth after instruction executes
  1531. // otherwise, make sure it matches all other branches to that target and what fell through to it
  1532. coll.stackDepth.Matches(myLabel);
  1533. }
  1534. public override void DebString(StringBuilder sb)
  1535. {
  1536. base.DebString(sb);
  1537. sb.Append(myLabel.name);
  1538. }
  1539. public override void WriteOutOne(ScriptMyILGen ilGen)
  1540. {
  1541. ilGen.Emit(errorAt, opcode, myLabel);
  1542. }
  1543. /**
  1544. * @brief Conditional branches return the next inline followed by the branch target
  1545. * Unconditional branches return only the branch target
  1546. * But if the target is outside our scope (eg __retlbl), omit it from the list
  1547. */
  1548. protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
  1549. {
  1550. return new NNEnumerable(this, typeof(NNEnumerator));
  1551. }
  1552. private class NNEnumerator: NNEnumeratorBase
  1553. {
  1554. private GraphNodeEmitLabel gn;
  1555. private int index;
  1556. public NNEnumerator(GraphNodeEmitLabel gn)
  1557. {
  1558. this.gn = gn;
  1559. }
  1560. public override bool MoveNext()
  1561. {
  1562. switch(gn.opcode.FlowControl)
  1563. {
  1564. case FlowControl.Branch:
  1565. {
  1566. // unconditional branch just goes to target and nothing else
  1567. switch(index)
  1568. {
  1569. case 0:
  1570. {
  1571. nn = gn.myLabel.whereAmI;
  1572. index++;
  1573. return nn != null;
  1574. }
  1575. case 1:
  1576. {
  1577. return false;
  1578. }
  1579. }
  1580. throw new Exception();
  1581. }
  1582. case FlowControl.Cond_Branch:
  1583. {
  1584. // conditional branch goes inline and to target
  1585. switch(index)
  1586. {
  1587. case 0:
  1588. {
  1589. nn = gn.nextLin;
  1590. index++;
  1591. return true;
  1592. }
  1593. case 1:
  1594. {
  1595. nn = gn.myLabel.whereAmI;
  1596. index++;
  1597. return nn != null;
  1598. }
  1599. case 2:
  1600. {
  1601. return false;
  1602. }
  1603. }
  1604. throw new Exception();
  1605. }
  1606. default:
  1607. throw new Exception("unknown flow control " + gn.opcode.FlowControl.ToString() +
  1608. " of " + gn.opcode.ToString());
  1609. }
  1610. }
  1611. public override void Reset()
  1612. {
  1613. index = 0;
  1614. nn = null;
  1615. }
  1616. }
  1617. }
  1618. public class GraphNodeEmitLabelLeave: GraphNodeEmitLabel
  1619. {
  1620. public GraphNodeBlock unwindTo; // if unwinding, innermost finally block being unwound
  1621. // else, same as myTarget.whereAmI
  1622. // null if unwinding completely out of scope, eg, __retlbl
  1623. public GraphNodeEmitLabelLeave(ScriptCollector coll, Token errorAt, ScriptMyLabel myLabel) : base(coll, errorAt, OpCodes.Leave, myLabel)
  1624. {
  1625. }
  1626. /**
  1627. * @brief Leave instructions have exactly one unconditional next node.
  1628. * Either the given target if within the same try block
  1629. * or the beginning of the intervening finally block.
  1630. */
  1631. protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
  1632. {
  1633. return new NNEnumerable(this, typeof(NNEnumerator));
  1634. }
  1635. private class NNEnumerator: NNEnumeratorBase
  1636. {
  1637. private GraphNodeEmitLabelLeave gn;
  1638. private int index;
  1639. public NNEnumerator(GraphNodeEmitLabelLeave gn)
  1640. {
  1641. this.gn = gn;
  1642. }
  1643. public override bool MoveNext()
  1644. {
  1645. if(index == 0)
  1646. {
  1647. nn = gn.unwindTo;
  1648. index++;
  1649. return nn != null;
  1650. }
  1651. nn = null;
  1652. return false;
  1653. }
  1654. public override void Reset()
  1655. {
  1656. index = 0;
  1657. nn = null;
  1658. }
  1659. }
  1660. }
  1661. public class GraphNodeEmitLabels: GraphNodeEmit
  1662. {
  1663. public ScriptMyLabel[] myLabels;
  1664. public GraphNodeEmitLabels(ScriptCollector coll, Token errorAt, OpCode opcode, ScriptMyLabel[] myLabels) : base(coll, errorAt, opcode)
  1665. {
  1666. this.myLabels = myLabels;
  1667. }
  1668. public override void ChainLin()
  1669. {
  1670. base.ChainLin();
  1671. switch(opcode.ToString())
  1672. {
  1673. case "switch":
  1674. {
  1675. coll.stackDepth.Pop(typeof(int));
  1676. break;
  1677. }
  1678. default:
  1679. throw new Exception("unknown opcode " + opcode.ToString());
  1680. }
  1681. // if a target doesn't have a depth yet, set its depth to the depth after instruction executes
  1682. // otherwise, make sure it matches all other branches to that target and what fell through to it
  1683. foreach(ScriptMyLabel myLabel in myLabels)
  1684. {
  1685. coll.stackDepth.Matches(myLabel);
  1686. }
  1687. }
  1688. public override void DebString(StringBuilder sb)
  1689. {
  1690. base.DebString(sb);
  1691. bool first = true;
  1692. foreach(ScriptMyLabel lbl in myLabels)
  1693. {
  1694. if(!first)
  1695. sb.Append(',');
  1696. sb.Append(lbl.name);
  1697. first = false;
  1698. }
  1699. }
  1700. public override void WriteOutOne(ScriptMyILGen ilGen)
  1701. {
  1702. ilGen.Emit(errorAt, opcode, myLabels);
  1703. }
  1704. /**
  1705. * @brief Return list of all labels followed by the next linear instruction
  1706. * But if the target is outside our scope (eg __retlbl), omit it from the list
  1707. */
  1708. protected override System.Collections.Generic.IEnumerable<GraphNode> GetNNEnumerable()
  1709. {
  1710. return new NNEnumerable(this, typeof(NNEnumerator));
  1711. }
  1712. private class NNEnumerator: NNEnumeratorBase
  1713. {
  1714. private GraphNodeEmitLabels gn;
  1715. private int index;
  1716. public NNEnumerator(GraphNodeEmitLabels gn)
  1717. {
  1718. this.gn = gn;
  1719. }
  1720. public override bool MoveNext()
  1721. {
  1722. // Return next from list of switch case labels.
  1723. while(index < gn.myLabels.Length)
  1724. {
  1725. nn = gn.myLabels[index++].whereAmI;
  1726. if(nn != null)
  1727. return true;
  1728. }
  1729. // If all ran out, the switch instruction falls through.
  1730. if(index == gn.myLabels.Length)
  1731. {
  1732. index++;
  1733. nn = gn.nextLin;
  1734. return true;
  1735. }
  1736. // Even ran out of that, say there's nothing more.
  1737. nn = null;
  1738. return false;
  1739. }
  1740. public override void Reset()
  1741. {
  1742. index = 0;
  1743. nn = null;
  1744. }
  1745. }
  1746. }
  1747. public class GraphNodeEmitIntMeth: GraphNodeEmit
  1748. {
  1749. public ScriptObjWriter method;
  1750. public GraphNodeEmitIntMeth(ScriptCollector coll, Token errorAt, OpCode opcode, ScriptObjWriter method) : base(coll, errorAt, opcode)
  1751. {
  1752. this.method = method;
  1753. }
  1754. public override void ChainLin()
  1755. {
  1756. base.ChainLin();
  1757. switch(opcode.ToString())
  1758. {
  1759. case "call":
  1760. {
  1761. // calls have Varpop so pop the number of arguments
  1762. // they are all static so there is no separate 'this' parameter
  1763. coll.stackDepth.Pop(this.method.argTypes);
  1764. // calls are also Varpush so they push a return value iff non-void
  1765. if(this.method.retType != typeof(void))
  1766. coll.stackDepth.Push(this.method.retType);
  1767. break;
  1768. }
  1769. default:
  1770. throw new Exception("unknown opcode " + opcode.ToString());
  1771. }
  1772. }
  1773. public override void DebString(StringBuilder sb)
  1774. {
  1775. base.DebString(sb);
  1776. sb.Append(method.methName);
  1777. }
  1778. public override void WriteOutOne(ScriptMyILGen ilGen)
  1779. {
  1780. ilGen.Emit(errorAt, opcode, method);
  1781. }
  1782. }
  1783. public class GraphNodeEmitExtMeth: GraphNodeEmit
  1784. {
  1785. public MethodInfo method;
  1786. public GraphNodeEmitExtMeth(ScriptCollector coll, Token errorAt, OpCode opcode, MethodInfo method) : base(coll, errorAt, opcode)
  1787. {
  1788. this.method = method;
  1789. }
  1790. public override void ChainLin()
  1791. {
  1792. base.ChainLin();
  1793. switch(opcode.ToString())
  1794. {
  1795. case "call":
  1796. case "callvirt":
  1797. {
  1798. // calls have Varpop so pop the number of arguments
  1799. coll.stackDepth.Pop(this.method.GetParameters());
  1800. if((this.method.CallingConvention & CallingConventions.HasThis) != 0)
  1801. {
  1802. coll.stackDepth.Pop(method.DeclaringType);
  1803. }
  1804. // calls are also Varpush so they push a return value iff non-void
  1805. if(this.method.ReturnType != typeof(void))
  1806. coll.stackDepth.Push(this.method.ReturnType);
  1807. break;
  1808. }
  1809. default:
  1810. throw new Exception("unknown opcode " + opcode.ToString());
  1811. }
  1812. }
  1813. public override void DebString(StringBuilder sb)
  1814. {
  1815. base.DebString(sb);
  1816. sb.Append(method.Name);
  1817. }
  1818. public override void WriteOutOne(ScriptMyILGen ilGen)
  1819. {
  1820. ilGen.Emit(errorAt, opcode, method);
  1821. }
  1822. }
  1823. public class GraphNodeEmitCtor: GraphNodeEmit
  1824. {
  1825. public ConstructorInfo ctor;
  1826. public GraphNodeEmitCtor(ScriptCollector coll, Token errorAt, OpCode opcode, ConstructorInfo ctor) : base(coll, errorAt, opcode)
  1827. {
  1828. this.ctor = ctor;
  1829. }
  1830. public override void ChainLin()
  1831. {
  1832. base.ChainLin();
  1833. switch(opcode.ToString())
  1834. {
  1835. case "newobj":
  1836. {
  1837. coll.stackDepth.Pop(ctor.GetParameters());
  1838. coll.stackDepth.Push(ctor.DeclaringType);
  1839. break;
  1840. }
  1841. default:
  1842. throw new Exception("unknown opcode " + opcode.ToString());
  1843. }
  1844. }
  1845. public override void DebString(StringBuilder sb)
  1846. {
  1847. base.DebString(sb);
  1848. sb.Append(ctor.ReflectedType.Name);
  1849. }
  1850. public override void WriteOutOne(ScriptMyILGen ilGen)
  1851. {
  1852. ilGen.Emit(errorAt, opcode, ctor);
  1853. }
  1854. }
  1855. public class GraphNodeEmitDouble: GraphNodeEmit
  1856. {
  1857. public double value;
  1858. public GraphNodeEmitDouble(ScriptCollector coll, Token errorAt, OpCode opcode, double value) : base(coll, errorAt, opcode)
  1859. {
  1860. this.value = value;
  1861. }
  1862. public override void ChainLin()
  1863. {
  1864. base.ChainLin();
  1865. switch(opcode.ToString())
  1866. {
  1867. case "ldc.r8":
  1868. coll.stackDepth.Push(typeof(double));
  1869. break;
  1870. default:
  1871. throw new Exception("unknown opcode " + opcode.ToString());
  1872. }
  1873. }
  1874. public override void DebString(StringBuilder sb)
  1875. {
  1876. base.DebString(sb);
  1877. sb.Append(value);
  1878. }
  1879. public override void WriteOutOne(ScriptMyILGen ilGen)
  1880. {
  1881. ilGen.Emit(errorAt, opcode, value);
  1882. }
  1883. }
  1884. public class GraphNodeEmitFloat: GraphNodeEmit
  1885. {
  1886. public float value;
  1887. public GraphNodeEmitFloat(ScriptCollector coll, Token errorAt, OpCode opcode, float value) : base(coll, errorAt, opcode)
  1888. {
  1889. this.value = value;
  1890. }
  1891. public override void ChainLin()
  1892. {
  1893. base.ChainLin();
  1894. switch(opcode.ToString())
  1895. {
  1896. case "ldc.r4":
  1897. coll.stackDepth.Push(typeof(float));
  1898. break;
  1899. default:
  1900. throw new Exception("unknown opcode " + opcode.ToString());
  1901. }
  1902. }
  1903. public override void DebString(StringBuilder sb)
  1904. {
  1905. base.DebString(sb);
  1906. sb.Append(value);
  1907. }
  1908. public override void WriteOutOne(ScriptMyILGen ilGen)
  1909. {
  1910. ilGen.Emit(errorAt, opcode, value);
  1911. }
  1912. }
  1913. public class GraphNodeEmitInt: GraphNodeEmit
  1914. {
  1915. public int value;
  1916. public GraphNodeEmitInt(ScriptCollector coll, Token errorAt, OpCode opcode, int value) : base(coll, errorAt, opcode)
  1917. {
  1918. this.value = value;
  1919. }
  1920. public override void ChainLin()
  1921. {
  1922. base.ChainLin();
  1923. switch(opcode.ToString())
  1924. {
  1925. case "ldarg":
  1926. case "ldarg.s":
  1927. coll.stackDepth.Push(coll.wrapped.argTypes[value]);
  1928. break;
  1929. case "ldarga":
  1930. case "ldarga.s":
  1931. coll.stackDepth.Push(coll.wrapped.argTypes[value].MakeByRefType());
  1932. break;
  1933. case "starg":
  1934. case "starg.s":
  1935. coll.stackDepth.Pop(coll.wrapped.argTypes[value]);
  1936. break;
  1937. case "ldc.i4":
  1938. case "ldc.i4.s":
  1939. coll.stackDepth.Push(typeof(int));
  1940. break;
  1941. default:
  1942. throw new Exception("unknown opcode " + opcode.ToString());
  1943. }
  1944. }
  1945. public override void DebString(StringBuilder sb)
  1946. {
  1947. base.DebString(sb);
  1948. sb.Append(value);
  1949. }
  1950. public override void WriteOutOne(ScriptMyILGen ilGen)
  1951. {
  1952. ilGen.Emit(errorAt, opcode, value);
  1953. }
  1954. }
  1955. public class GraphNodeEmitString: GraphNodeEmit
  1956. {
  1957. public string value;
  1958. public GraphNodeEmitString(ScriptCollector coll, Token errorAt, OpCode opcode, string value) : base(coll, errorAt, opcode)
  1959. {
  1960. this.value = value;
  1961. }
  1962. public override void ChainLin()
  1963. {
  1964. base.ChainLin();
  1965. switch(opcode.ToString())
  1966. {
  1967. case "ldstr":
  1968. coll.stackDepth.Push(typeof(string));
  1969. break;
  1970. default:
  1971. throw new Exception("unknown opcode " + opcode.ToString());
  1972. }
  1973. }
  1974. public override void DebString(StringBuilder sb)
  1975. {
  1976. base.DebString(sb);
  1977. sb.Append("\"");
  1978. sb.Append(value);
  1979. sb.Append("\"");
  1980. }
  1981. public override void WriteOutOne(ScriptMyILGen ilGen)
  1982. {
  1983. ilGen.Emit(errorAt, opcode, value);
  1984. }
  1985. }
  1986. public class GraphNodeMarkLabel: GraphNodeBlock
  1987. {
  1988. public ScriptMyLabel myLabel;
  1989. public GraphNodeMarkLabel(ScriptCollector coll, ScriptMyLabel myLabel) : base(coll)
  1990. {
  1991. this.myLabel = myLabel;
  1992. }
  1993. public override void ChainLin()
  1994. {
  1995. base.ChainLin();
  1996. // if previous instruction can fall through to this label,
  1997. // if the label doesn't yet have a stack depth, mark it with current stack depth
  1998. // else, the label's stack depth from forward branches and current stack depth must match
  1999. // else,
  2000. // label must have had a forward branch to it so we can know stack depth
  2001. // set the current stack depth to the label's stack depth as of that forward branch
  2002. if(myLabel.whereAmI.prevLin.CanFallThrough())
  2003. {
  2004. coll.stackDepth.Matches(myLabel);
  2005. }
  2006. else
  2007. {
  2008. if(myLabel.stackDepth == null)
  2009. {
  2010. throw new Exception("stack depth unknown at " + myLabel.name);
  2011. }
  2012. coll.stackDepth.Clear();
  2013. int n = myLabel.stackDepth.Length;
  2014. for(int i = 0; i < n; i++)
  2015. {
  2016. coll.stackDepth.Push(myLabel.stackDepth[i], myLabel.stackBoxeds[i]);
  2017. }
  2018. }
  2019. }
  2020. public override void DebString(StringBuilder sb)
  2021. {
  2022. sb.Append(myLabel.name);
  2023. sb.Append(':');
  2024. if(myLabel.stackDepth != null)
  2025. {
  2026. sb.Append(" [");
  2027. sb.Append(myLabel.stackDepth.Length);
  2028. sb.Append(']');
  2029. }
  2030. }
  2031. public override void WriteOutOne(ScriptMyILGen ilGen)
  2032. {
  2033. ilGen.MarkLabel(myLabel);
  2034. }
  2035. }
  2036. /**
  2037. * @brief Generates enumerator that steps through list of nodes that can
  2038. * possibly be next in a flow-control sense.
  2039. */
  2040. public class NNEnumerable: System.Collections.Generic.IEnumerable<GraphNode>
  2041. {
  2042. private object[] cps;
  2043. private ConstructorInfo ci;
  2044. public NNEnumerable(GraphNode gn, Type nnEnumeratorType)
  2045. {
  2046. this.cps = new object[] { gn };
  2047. this.ci = nnEnumeratorType.GetConstructor(new Type[] { gn.GetType() });
  2048. }
  2049. System.Collections.Generic.IEnumerator<GraphNode> System.Collections.Generic.IEnumerable<GraphNode>.GetEnumerator()
  2050. {
  2051. return (System.Collections.Generic.IEnumerator<GraphNode>)ci.Invoke(cps);
  2052. }
  2053. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  2054. {
  2055. return (System.Collections.IEnumerator)ci.Invoke(cps);
  2056. }
  2057. }
  2058. /**
  2059. * @brief Steps through list of nodes that can possible be next in a flow-control sense.
  2060. */
  2061. public abstract class NNEnumeratorBase: System.Collections.Generic.IEnumerator<GraphNode>
  2062. {
  2063. protected GraphNode nn;
  2064. public abstract bool MoveNext();
  2065. public abstract void Reset();
  2066. GraphNode System.Collections.Generic.IEnumerator<GraphNode>.Current
  2067. {
  2068. get
  2069. {
  2070. return this.nn;
  2071. }
  2072. }
  2073. object System.Collections.IEnumerator.Current
  2074. {
  2075. get
  2076. {
  2077. return this.nn;
  2078. }
  2079. }
  2080. void System.IDisposable.Dispose()
  2081. {
  2082. }
  2083. }
  2084. public class ScriptCollector: ScriptMyILGen
  2085. {
  2086. public static readonly bool DEBUG = false;
  2087. public ScriptObjWriter wrapped;
  2088. public GraphNode firstLin, lastLin;
  2089. private bool resolvedSomething;
  2090. private int resolveSequence;
  2091. private int excBlkSeqNos;
  2092. public StackDepth stackDepth = new StackDepth();
  2093. public GraphNodeBeginExceptionBlock curTryBlock = null; // pushed at beginning of try
  2094. // popped at BEGINNING of catch/finally
  2095. public GraphNodeBeginExceptionBlock curExcBlock = null; // pushed at beginning of try
  2096. // popped at END of catch/finally
  2097. private List<ScriptMyLocal> declaredLocals = new List<ScriptMyLocal>();
  2098. private List<ScriptMyLabel> definedLabels = new List<ScriptMyLabel>();
  2099. public string methName
  2100. {
  2101. get
  2102. {
  2103. return wrapped.methName;
  2104. }
  2105. }
  2106. /**
  2107. * @brief Wrap the optimizer around the ScriptObjWriter to collect the instruction stream.
  2108. * All stream-writing calls get saved to our graph nodes instead of being written to object file.
  2109. */
  2110. public ScriptCollector(ScriptObjWriter wrapped)
  2111. {
  2112. this.wrapped = wrapped;
  2113. GraphNodeBegin gnb = new GraphNodeBegin(this);
  2114. this.firstLin = gnb;
  2115. this.lastLin = gnb;
  2116. }
  2117. public ScriptMyLocal DeclareLocal(Type type, string name)
  2118. {
  2119. ScriptMyLocal loc = new ScriptMyLocal();
  2120. loc.name = name;
  2121. loc.type = type;
  2122. loc.number = wrapped.localNumber++;
  2123. declaredLocals.Add(loc);
  2124. return loc;
  2125. }
  2126. public ScriptMyLabel DefineLabel(string name)
  2127. {
  2128. ScriptMyLabel lbl = new ScriptMyLabel();
  2129. lbl.name = name;
  2130. lbl.number = wrapped.labelNumber++;
  2131. definedLabels.Add(lbl);
  2132. return lbl;
  2133. }
  2134. public void BeginExceptionBlock()
  2135. {
  2136. GraphNodeBeginExceptionBlock tryBlock = new GraphNodeBeginExceptionBlock(this);
  2137. tryBlock.ChainLin();
  2138. tryBlock.excBlkSeqNo = ++this.excBlkSeqNos;
  2139. this.curExcBlock = tryBlock;
  2140. this.curTryBlock = tryBlock;
  2141. }
  2142. public void BeginCatchBlock(Type excType)
  2143. {
  2144. GraphNodeBeginCatchBlock catchBlock = new GraphNodeBeginCatchBlock(this, excType);
  2145. catchBlock.ChainLin();
  2146. if(curExcBlock.catchFinallyBlock != null)
  2147. throw new Exception("only one catch/finally allowed per try");
  2148. curExcBlock.catchFinallyBlock = catchBlock;
  2149. curTryBlock = curExcBlock.tryBlock;
  2150. }
  2151. public void BeginFinallyBlock()
  2152. {
  2153. GraphNodeBeginFinallyBlock finallyBlock = new GraphNodeBeginFinallyBlock(this);
  2154. finallyBlock.ChainLin();
  2155. if(curExcBlock.catchFinallyBlock != null)
  2156. throw new Exception("only one catch/finally allowed per try");
  2157. curExcBlock.catchFinallyBlock = finallyBlock;
  2158. curTryBlock = curExcBlock.tryBlock;
  2159. }
  2160. public void EndExceptionBlock()
  2161. {
  2162. GraphNodeEndExceptionBlock endExcBlock = new GraphNodeEndExceptionBlock(this);
  2163. endExcBlock.ChainLin();
  2164. curExcBlock.endExcBlock = endExcBlock;
  2165. curTryBlock = curExcBlock.tryBlock;
  2166. curExcBlock = curExcBlock.excBlock;
  2167. }
  2168. public void Emit(Token errorAt, OpCode opcode)
  2169. {
  2170. if(opcode == OpCodes.Endfinally)
  2171. {
  2172. new GraphNodeEmitNullEndfinally(this, errorAt).ChainLin();
  2173. }
  2174. else
  2175. {
  2176. new GraphNodeEmitNull(this, errorAt, opcode).ChainLin();
  2177. }
  2178. }
  2179. public void Emit(Token errorAt, OpCode opcode, FieldInfo field)
  2180. {
  2181. if(field == null)
  2182. throw new ArgumentNullException("field");
  2183. new GraphNodeEmitField(this, errorAt, opcode, field).ChainLin();
  2184. }
  2185. public void Emit(Token errorAt, OpCode opcode, ScriptMyLocal myLocal)
  2186. {
  2187. new GraphNodeEmitLocal(this, errorAt, opcode, myLocal).ChainLin();
  2188. }
  2189. public void Emit(Token errorAt, OpCode opcode, Type type)
  2190. {
  2191. new GraphNodeEmitType(this, errorAt, opcode, type).ChainLin();
  2192. }
  2193. public void Emit(Token errorAt, OpCode opcode, ScriptMyLabel myLabel)
  2194. {
  2195. if(opcode == OpCodes.Leave)
  2196. {
  2197. new GraphNodeEmitLabelLeave(this, errorAt, myLabel).ChainLin();
  2198. }
  2199. else
  2200. {
  2201. new GraphNodeEmitLabel(this, errorAt, opcode, myLabel).ChainLin();
  2202. }
  2203. }
  2204. public void Emit(Token errorAt, OpCode opcode, ScriptMyLabel[] myLabels)
  2205. {
  2206. new GraphNodeEmitLabels(this, errorAt, opcode, myLabels).ChainLin();
  2207. }
  2208. public void Emit(Token errorAt, OpCode opcode, ScriptObjWriter method)
  2209. {
  2210. if(method == null)
  2211. throw new ArgumentNullException("method");
  2212. new GraphNodeEmitIntMeth(this, errorAt, opcode, method).ChainLin();
  2213. }
  2214. public void Emit(Token errorAt, OpCode opcode, MethodInfo method)
  2215. {
  2216. if(method == null)
  2217. throw new ArgumentNullException("method");
  2218. new GraphNodeEmitExtMeth(this, errorAt, opcode, method).ChainLin();
  2219. }
  2220. public void Emit(Token errorAt, OpCode opcode, ConstructorInfo ctor)
  2221. {
  2222. if(ctor == null)
  2223. throw new ArgumentNullException("ctor");
  2224. new GraphNodeEmitCtor(this, errorAt, opcode, ctor).ChainLin();
  2225. }
  2226. public void Emit(Token errorAt, OpCode opcode, double value)
  2227. {
  2228. new GraphNodeEmitDouble(this, errorAt, opcode, value).ChainLin();
  2229. }
  2230. public void Emit(Token errorAt, OpCode opcode, float value)
  2231. {
  2232. new GraphNodeEmitFloat(this, errorAt, opcode, value).ChainLin();
  2233. }
  2234. public void Emit(Token errorAt, OpCode opcode, int value)
  2235. {
  2236. new GraphNodeEmitInt(this, errorAt, opcode, value).ChainLin();
  2237. }
  2238. public void Emit(Token errorAt, OpCode opcode, string value)
  2239. {
  2240. new GraphNodeEmitString(this, errorAt, opcode, value).ChainLin();
  2241. }
  2242. public void MarkLabel(ScriptMyLabel myLabel)
  2243. {
  2244. myLabel.whereAmI = new GraphNodeMarkLabel(this, myLabel);
  2245. myLabel.whereAmI.ChainLin();
  2246. }
  2247. /**
  2248. * @brief Write the whole graph out to the object file.
  2249. */
  2250. public ScriptMyILGen WriteOutAll()
  2251. {
  2252. foreach(ScriptMyLocal loc in declaredLocals)
  2253. {
  2254. if(loc.isReferenced)
  2255. wrapped.DeclareLocal(loc);
  2256. }
  2257. foreach(ScriptMyLabel lbl in definedLabels)
  2258. {
  2259. wrapped.DefineLabel(lbl);
  2260. }
  2261. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2262. {
  2263. gn.WriteOutOne(wrapped);
  2264. }
  2265. return wrapped;
  2266. }
  2267. /**
  2268. * @brief Perform optimizations.
  2269. */
  2270. public void Optimize()
  2271. {
  2272. if(curExcBlock != null)
  2273. throw new Exception("exception block still open");
  2274. // If an instruction says it doesn't fall through, remove all instructions to
  2275. // the end of the block.
  2276. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2277. {
  2278. if(!gn.CanFallThrough())
  2279. {
  2280. GraphNode nn;
  2281. while(((nn = gn.nextLin) != null) && !(nn is GraphNodeBlock) &&
  2282. !(nn is GraphNodeEndExceptionBlock))
  2283. {
  2284. if((gn.nextLin = nn.nextLin) != null)
  2285. {
  2286. nn.nextLin.prevLin = gn;
  2287. }
  2288. }
  2289. }
  2290. }
  2291. // Scan for OpCodes.Leave instructions.
  2292. // For each found, its target for flow analysis purposes is the beginning of the corresponding
  2293. // finally block. And the end of the finally block gets a conditional branch target of the
  2294. // leave instruction's target. A leave instruction can unwind zero or more finally blocks.
  2295. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2296. {
  2297. if(gn is GraphNodeEmitLabelLeave)
  2298. {
  2299. GraphNodeEmitLabelLeave leaveInstr = (GraphNodeEmitLabelLeave)gn; // the leave instruction
  2300. GraphNodeMarkLabel leaveTarget = leaveInstr.myLabel.whereAmI; // label being targeted by leave
  2301. GraphNodeBeginExceptionBlock leaveTargetsTryBlock = // try block directly enclosing leave target
  2302. (leaveTarget == null) ? null : leaveTarget.tryBlock; // ...it must not be unwound
  2303. // Step through try { }s from the leave instruction towards its target looking for try { }s with finally { }s.
  2304. // The leave instruction unconditionally branches to the beginning of the innermost one found.
  2305. // The end of the last one found conditionally branches to the leave instruction's target.
  2306. // If none found, the leave is a simple unconditional branch to its target.
  2307. GraphNodeBeginFinallyBlock innerFinallyBlock = null;
  2308. for(GraphNodeBeginExceptionBlock tryBlock = leaveInstr.tryBlock;
  2309. tryBlock != leaveTargetsTryBlock;
  2310. tryBlock = tryBlock.tryBlock)
  2311. {
  2312. if(tryBlock == null)
  2313. throw new Exception("leave target not at or outer to leave instruction");
  2314. GraphNodeCatchFinallyBlock cfb = tryBlock.catchFinallyBlock;
  2315. if(cfb is GraphNodeBeginFinallyBlock)
  2316. {
  2317. if(innerFinallyBlock == null)
  2318. {
  2319. leaveInstr.unwindTo = cfb;
  2320. }
  2321. innerFinallyBlock = (GraphNodeBeginFinallyBlock)cfb;
  2322. }
  2323. }
  2324. // The end of the outermost finally being unwound can conditionally jump to the target of the leave instruction.
  2325. // In the case of no finallies being unwound, the leave is just a simple unconditional branch.
  2326. if(innerFinallyBlock == null)
  2327. {
  2328. leaveInstr.unwindTo = leaveTarget;
  2329. }
  2330. else if(!innerFinallyBlock.leaveTargets.Contains(leaveTarget))
  2331. {
  2332. innerFinallyBlock.leaveTargets.Add(leaveTarget);
  2333. }
  2334. }
  2335. }
  2336. // See which variables a particular block reads before writing.
  2337. // This just considers the block itself and nothing that it branches to or fallsthru to.
  2338. GraphNodeBlock currentBlock = null;
  2339. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2340. {
  2341. if(gn is GraphNodeBlock)
  2342. currentBlock = (GraphNodeBlock)gn;
  2343. ScriptMyLocal rdlcl = gn.ReadsLocal();
  2344. if((rdlcl != null) &&
  2345. !currentBlock.localsWrittenBeforeRead.Contains(rdlcl) &&
  2346. !currentBlock.localsReadBeforeWritten.Contains(rdlcl))
  2347. {
  2348. currentBlock.localsReadBeforeWritten.Add(rdlcl);
  2349. }
  2350. ScriptMyLocal wrlcl = gn.WritesLocal();
  2351. if((wrlcl != null) &&
  2352. !currentBlock.localsWrittenBeforeRead.Contains(wrlcl) &&
  2353. !currentBlock.localsReadBeforeWritten.Contains(wrlcl))
  2354. {
  2355. currentBlock.localsWrittenBeforeRead.Add(wrlcl);
  2356. }
  2357. }
  2358. // For every block we branch to, add that blocks readables to our list of readables,
  2359. // because we need to have those values valid on entry to our block. But if we write the
  2360. // variable before we can possibly branch to that block, then we don't need to have it valid
  2361. // on entry to our block. So basically it looks like the branch instruction is reading
  2362. // everything required by any blocks it can branch to.
  2363. do
  2364. {
  2365. resolvedSomething = false;
  2366. resolveSequence++;
  2367. ResolveBlock((GraphNodeBlock)firstLin);
  2368. } while(resolvedSomething);
  2369. // Repeat the cutting loops as long as we keep finding stuff.
  2370. bool didSomething;
  2371. do
  2372. {
  2373. didSomething = false;
  2374. // Strip out ldc.i4.1/xor/ldc.i4.1/xor
  2375. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2376. {
  2377. if(!(gn is GraphNodeEmit))
  2378. continue;
  2379. GraphNodeEmit xor2 = (GraphNodeEmit)gn;
  2380. if(xor2.opcode != OpCodes.Xor)
  2381. continue;
  2382. if(!(xor2.prevLin is GraphNodeEmit))
  2383. continue;
  2384. GraphNodeEmit ld12 = (GraphNodeEmit)xor2.prevLin;
  2385. if(ld12.opcode != OpCodes.Ldc_I4_1)
  2386. continue;
  2387. if(!(ld12.prevLin is GraphNodeEmit))
  2388. continue;
  2389. GraphNodeEmit xor1 = (GraphNodeEmit)ld12.prevLin;
  2390. if(xor1.opcode != OpCodes.Xor)
  2391. continue;
  2392. if(!(xor2.prevLin is GraphNodeEmit))
  2393. continue;
  2394. GraphNodeEmit ld11 = (GraphNodeEmit)xor1.prevLin;
  2395. if(ld11.opcode != OpCodes.Ldc_I4_1)
  2396. continue;
  2397. ld11.prevLin.nextLin = xor2.nextLin;
  2398. xor2.nextLin.prevLin = ld11.prevLin;
  2399. didSomething = true;
  2400. }
  2401. // Replace c{cond}/ldc.i4.1/xor/br{false,true} -> c{cond}/br{true,false}
  2402. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2403. {
  2404. if(!(gn is GraphNodeEmit))
  2405. continue;
  2406. GraphNodeEmit brft = (GraphNodeEmit)gn;
  2407. if((brft.opcode != OpCodes.Brfalse) && (brft.opcode != OpCodes.Brtrue))
  2408. continue;
  2409. if(!(brft.prevLin is GraphNodeEmit))
  2410. continue;
  2411. GraphNodeEmit xor = (GraphNodeEmit)brft.prevLin;
  2412. if(xor.opcode != OpCodes.Xor)
  2413. continue;
  2414. if(!(xor.prevLin is GraphNodeEmit))
  2415. continue;
  2416. GraphNodeEmit ldc = (GraphNodeEmit)xor.prevLin;
  2417. if(ldc.opcode != OpCodes.Ldc_I4_1)
  2418. continue;
  2419. if(!(ldc.prevLin is GraphNodeEmit))
  2420. continue;
  2421. GraphNodeEmit cmp = (GraphNodeEmit)ldc.prevLin;
  2422. if(cmp.opcode.StackBehaviourPop != StackBehaviour.Pop1_pop1)
  2423. continue;
  2424. if(cmp.opcode.StackBehaviourPush != StackBehaviour.Pushi)
  2425. continue;
  2426. cmp.nextLin = brft;
  2427. brft.prevLin = cmp;
  2428. brft.opcode = (brft.opcode == OpCodes.Brfalse) ? OpCodes.Brtrue : OpCodes.Brfalse;
  2429. didSomething = true;
  2430. }
  2431. // Replace c{cond}/br{false,true} -> b{!,}{cond}
  2432. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2433. {
  2434. if(!(gn is GraphNodeEmit))
  2435. continue;
  2436. GraphNodeEmit brft = (GraphNodeEmit)gn;
  2437. if((brft.opcode != OpCodes.Brfalse) && (brft.opcode != OpCodes.Brtrue))
  2438. continue;
  2439. if(!(brft.prevLin is GraphNodeEmit))
  2440. continue;
  2441. GraphNodeEmit cmp = (GraphNodeEmit)brft.prevLin;
  2442. if(cmp.opcode.StackBehaviourPop != StackBehaviour.Pop1_pop1)
  2443. continue;
  2444. if(cmp.opcode.StackBehaviourPush != StackBehaviour.Pushi)
  2445. continue;
  2446. cmp.prevLin.nextLin = brft;
  2447. brft.prevLin = cmp.prevLin;
  2448. bool brtru = (brft.opcode == OpCodes.Brtrue);
  2449. if(cmp.opcode == OpCodes.Ceq)
  2450. brft.opcode = brtru ? OpCodes.Beq : OpCodes.Bne_Un;
  2451. else if(cmp.opcode == OpCodes.Cgt)
  2452. brft.opcode = brtru ? OpCodes.Bgt : OpCodes.Ble;
  2453. else if(cmp.opcode == OpCodes.Cgt_Un)
  2454. brft.opcode = brtru ? OpCodes.Bgt_Un : OpCodes.Ble_Un;
  2455. else if(cmp.opcode == OpCodes.Clt)
  2456. brft.opcode = brtru ? OpCodes.Blt : OpCodes.Bge;
  2457. else if(cmp.opcode == OpCodes.Clt_Un)
  2458. brft.opcode = brtru ? OpCodes.Blt_Un : OpCodes.Bge_Un;
  2459. else
  2460. throw new Exception();
  2461. didSomething = true;
  2462. }
  2463. // Replace ld{c.i4.0,null}/br{ne.un,eq} -> br{true,false}
  2464. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2465. {
  2466. if(!(gn is GraphNodeEmit))
  2467. continue;
  2468. GraphNodeEmit brcc = (GraphNodeEmit)gn;
  2469. if((brcc.opcode != OpCodes.Bne_Un) && (brcc.opcode != OpCodes.Beq))
  2470. continue;
  2471. if(!(brcc.prevLin is GraphNodeEmit))
  2472. continue;
  2473. GraphNodeEmit ldc0 = (GraphNodeEmit)brcc.prevLin;
  2474. if((ldc0.opcode != OpCodes.Ldc_I4_0) && (ldc0.opcode != OpCodes.Ldnull))
  2475. continue;
  2476. ldc0.prevLin.nextLin = brcc;
  2477. brcc.prevLin = ldc0.prevLin;
  2478. brcc.opcode = (brcc.opcode == OpCodes.Bne_Un) ? OpCodes.Brtrue : OpCodes.Brfalse;
  2479. didSomething = true;
  2480. }
  2481. // Replace:
  2482. // ldloc v1
  2483. // stloc v2
  2484. // ld<anything> except ld<anything> v2
  2485. // ldloc v2
  2486. // ...v2 unreferenced hereafter
  2487. // With:
  2488. // ld<anything> except ld<anything> v2
  2489. // ldloc v1
  2490. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2491. {
  2492. // check for 'ldloc v1' instruction
  2493. if(!(gn is GraphNodeEmitLocal))
  2494. continue;
  2495. GraphNodeEmitLocal ldlv1 = (GraphNodeEmitLocal)gn;
  2496. if(ldlv1.opcode != OpCodes.Ldloc)
  2497. continue;
  2498. // check for 'stloc v2' instruction
  2499. if(!(ldlv1.nextLin is GraphNodeEmitLocal))
  2500. continue;
  2501. GraphNodeEmitLocal stlv2 = (GraphNodeEmitLocal)ldlv1.nextLin;
  2502. if(stlv2.opcode != OpCodes.Stloc)
  2503. continue;
  2504. // check for 'ld<anything> except ld<anything> v2' instruction
  2505. if(!(stlv2.nextLin is GraphNodeEmit))
  2506. continue;
  2507. GraphNodeEmit ldany = (GraphNodeEmit)stlv2.nextLin;
  2508. if(!ldany.opcode.ToString().StartsWith("ld"))
  2509. continue;
  2510. if((ldany is GraphNodeEmitLocal) &&
  2511. ((GraphNodeEmitLocal)ldany).myLocal == stlv2.myLocal)
  2512. continue;
  2513. // check for 'ldloc v2' instruction
  2514. if(!(ldany.nextLin is GraphNodeEmitLocal))
  2515. continue;
  2516. GraphNodeEmitLocal ldlv2 = (GraphNodeEmitLocal)ldany.nextLin;
  2517. if(ldlv2.opcode != OpCodes.Ldloc)
  2518. continue;
  2519. if(ldlv2.myLocal != stlv2.myLocal)
  2520. continue;
  2521. // check that v2 is not needed after this at all
  2522. if(IsLocalNeededAfterThis(ldlv2, ldlv2.myLocal))
  2523. continue;
  2524. // make 'ld<anything>...' the first instruction
  2525. ldany.prevLin = ldlv1.prevLin;
  2526. ldany.prevLin.nextLin = ldany;
  2527. // make 'ldloc v1' the second instruction
  2528. ldany.nextLin = ldlv1;
  2529. ldlv1.prevLin = ldany;
  2530. // and make 'ldloc v1' the last instruction
  2531. ldlv1.nextLin = ldlv2.nextLin;
  2532. ldlv1.nextLin.prevLin = ldlv1;
  2533. didSomething = true;
  2534. }
  2535. // Remove all the stloc/ldloc that are back-to-back without the local
  2536. // being needed afterwards. If it is needed afterwards, replace the
  2537. // stloc/ldloc with dup/stloc.
  2538. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2539. {
  2540. if((gn is GraphNodeEmitLocal) &&
  2541. (gn.prevLin is GraphNodeEmitLocal))
  2542. {
  2543. GraphNodeEmitLocal stloc = (GraphNodeEmitLocal)gn.prevLin;
  2544. GraphNodeEmitLocal ldloc = (GraphNodeEmitLocal)gn;
  2545. if((stloc.opcode == OpCodes.Stloc) &&
  2546. (ldloc.opcode == OpCodes.Ldloc) &&
  2547. (stloc.myLocal == ldloc.myLocal))
  2548. {
  2549. if(IsLocalNeededAfterThis(ldloc, ldloc.myLocal))
  2550. {
  2551. GraphNodeEmitNull dup = new GraphNodeEmitNull(this, stloc.errorAt, OpCodes.Dup);
  2552. dup.nextLin = stloc;
  2553. dup.prevLin = stloc.prevLin;
  2554. stloc.nextLin = ldloc.nextLin;
  2555. stloc.prevLin = dup;
  2556. dup.prevLin.nextLin = dup;
  2557. stloc.nextLin.prevLin = stloc;
  2558. gn = stloc;
  2559. }
  2560. else
  2561. {
  2562. stloc.prevLin.nextLin = ldloc.nextLin;
  2563. ldloc.nextLin.prevLin = stloc.prevLin;
  2564. gn = stloc.prevLin;
  2565. }
  2566. didSomething = true;
  2567. }
  2568. }
  2569. }
  2570. // Remove all write-only local variables, ie, those with no ldloc[a] references.
  2571. // Replace any stloc instructions with pops.
  2572. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2573. {
  2574. ScriptMyLocal rdlcl = gn.ReadsLocal();
  2575. if(rdlcl != null)
  2576. rdlcl.isReferenced = true;
  2577. }
  2578. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2579. {
  2580. ScriptMyLocal wrlcl = gn.WritesLocal();
  2581. if((wrlcl != null) && !wrlcl.isReferenced)
  2582. {
  2583. if(!(gn is GraphNodeEmitLocal) || (((GraphNodeEmitLocal)gn).opcode != OpCodes.Stloc))
  2584. {
  2585. throw new Exception("expecting stloc");
  2586. }
  2587. GraphNodeEmitNull pop = new GraphNodeEmitNull(this, ((GraphNodeEmit)gn).errorAt, OpCodes.Pop);
  2588. pop.nextLin = gn.nextLin;
  2589. pop.prevLin = gn.prevLin;
  2590. gn.nextLin.prevLin = pop;
  2591. gn.prevLin.nextLin = pop;
  2592. gn = pop;
  2593. didSomething = true;
  2594. }
  2595. }
  2596. // Remove any Ld<const>/Dup,Pop.
  2597. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2598. {
  2599. if((gn is GraphNodeEmit) &&
  2600. (gn.nextLin is GraphNodeEmit))
  2601. {
  2602. GraphNodeEmit gne = (GraphNodeEmit)gn;
  2603. GraphNodeEmit nne = (GraphNodeEmit)gn.nextLin;
  2604. if(gne.isPoppable && (nne.opcode == OpCodes.Pop))
  2605. {
  2606. gne.prevLin.nextLin = nne.nextLin;
  2607. nne.nextLin.prevLin = gne.prevLin;
  2608. gn = gne.prevLin;
  2609. didSomething = true;
  2610. }
  2611. }
  2612. }
  2613. } while(didSomething);
  2614. // Dump out the results.
  2615. if(DEBUG)
  2616. {
  2617. Console.WriteLine("");
  2618. Console.WriteLine(methName);
  2619. Console.WriteLine(" resolveSequence=" + this.resolveSequence);
  2620. Console.WriteLine(" Locals:");
  2621. foreach(ScriptMyLocal loc in declaredLocals)
  2622. {
  2623. Console.WriteLine(" " + loc.type.Name + " " + loc.name);
  2624. }
  2625. Console.WriteLine(" Labels:");
  2626. foreach(ScriptMyLabel lbl in definedLabels)
  2627. {
  2628. Console.WriteLine(" " + lbl.name);
  2629. }
  2630. Console.WriteLine(" Code:");
  2631. DumpCode();
  2632. }
  2633. }
  2634. private void DumpCode()
  2635. {
  2636. int linSeqNos = 0;
  2637. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2638. {
  2639. gn.linSeqNo = ++linSeqNos;
  2640. }
  2641. for(GraphNode gn = firstLin; gn != null; gn = gn.nextLin)
  2642. {
  2643. StringBuilder sb = new StringBuilder();
  2644. gn.DebStringExt(sb);
  2645. Console.WriteLine(sb.ToString());
  2646. if(gn is GraphNodeBlock)
  2647. {
  2648. GraphNodeBlock gnb = (GraphNodeBlock)gn;
  2649. foreach(ScriptMyLocal lcl in gnb.localsReadBeforeWritten)
  2650. {
  2651. Console.WriteLine(" reads " + lcl.name);
  2652. }
  2653. }
  2654. }
  2655. }
  2656. /**
  2657. * @brief Scan the given block for branches to other blocks.
  2658. * For any locals read by those blocks, mark them as being read by this block,
  2659. * provided this block has not written them by that point. This makes it look
  2660. * as though the branch instruction is reading all the locals needed by any
  2661. * target blocks.
  2662. */
  2663. private void ResolveBlock(GraphNodeBlock currentBlock)
  2664. {
  2665. if(currentBlock.hasBeenResolved == this.resolveSequence)
  2666. return;
  2667. // So we don't recurse forever on a backward branch.
  2668. currentBlock.hasBeenResolved = resolveSequence;
  2669. // Assume we haven't written any locals yet.
  2670. List<ScriptMyLocal> localsWrittenSoFar = new List<ScriptMyLocal>();
  2671. // Scan through the instructions in this block.
  2672. for(GraphNode gn = currentBlock; gn != null;)
  2673. {
  2674. // See if the instruction writes a local we don't know about yet.
  2675. ScriptMyLocal wrlcl = gn.WritesLocal();
  2676. if((wrlcl != null) && !localsWrittenSoFar.Contains(wrlcl))
  2677. {
  2678. localsWrittenSoFar.Add(wrlcl);
  2679. }
  2680. // Scan through all the possible next instructions after this.
  2681. // Note that if we are in the first part of a try/catch/finally block,
  2682. // every instruction conditionally branches to the beginning of the
  2683. // second part (the catch/finally block).
  2684. GraphNode nextFallthruNode = null;
  2685. foreach(GraphNode nn in gn.NextNodes)
  2686. {
  2687. if(nn is GraphNodeBlock)
  2688. {
  2689. // Start of a block, go through all locals needed by that block on entry.
  2690. GraphNodeBlock nextBlock = (GraphNodeBlock)nn;
  2691. ResolveBlock(nextBlock);
  2692. foreach(ScriptMyLocal readByNextBlock in nextBlock.localsReadBeforeWritten)
  2693. {
  2694. // If this block hasn't written it by now and this block doesn't already
  2695. // require it on entry, say this block requires it on entry.
  2696. if(!localsWrittenSoFar.Contains(readByNextBlock) &&
  2697. !currentBlock.localsReadBeforeWritten.Contains(readByNextBlock))
  2698. {
  2699. currentBlock.localsReadBeforeWritten.Add(readByNextBlock);
  2700. resolvedSomething = true;
  2701. }
  2702. }
  2703. }
  2704. else
  2705. {
  2706. // Not start of a block, should be normal fallthru instruction.
  2707. if(nextFallthruNode != null)
  2708. throw new Exception("more than one fallthru from " + gn.ToString());
  2709. nextFallthruNode = nn;
  2710. }
  2711. }
  2712. // Process next instruction if it isn't the start of a block.
  2713. if(nextFallthruNode == gn)
  2714. throw new Exception("can't fallthru to self");
  2715. gn = nextFallthruNode;
  2716. }
  2717. }
  2718. /**
  2719. * @brief Figure out whether the value in a local var is needed after the given instruction.
  2720. * True if we reach the end of the program on all branches before reading it
  2721. * True if we write the local var on all branches before reading it
  2722. * False otherwise
  2723. */
  2724. private bool IsLocalNeededAfterThis(GraphNode node, ScriptMyLocal local)
  2725. {
  2726. do
  2727. {
  2728. GraphNode nextFallthruNode = null;
  2729. foreach(GraphNode nn in node.NextNodes)
  2730. {
  2731. if(nn is GraphNodeBlock)
  2732. {
  2733. if(((GraphNodeBlock)nn).localsReadBeforeWritten.Contains(local))
  2734. {
  2735. return true;
  2736. }
  2737. }
  2738. else
  2739. {
  2740. nextFallthruNode = nn;
  2741. }
  2742. }
  2743. node = nextFallthruNode;
  2744. if(node == null)
  2745. return false;
  2746. if(node.ReadsLocal() == local)
  2747. return true;
  2748. } while(node.WritesLocal() != local);
  2749. return false;
  2750. }
  2751. public static void PadToLength(StringBuilder sb, int len, string str)
  2752. {
  2753. int pad = len - sb.Length;
  2754. if(pad < 0)
  2755. pad = 0;
  2756. sb.Append(str.PadLeft(pad));
  2757. }
  2758. }
  2759. }