tree-ssa-loop-prefetch.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081
  1. /* Array prefetching.
  2. Copyright (C) 2005-2015 Free Software Foundation, Inc.
  3. This file is part of GCC.
  4. GCC is free software; you can redistribute it and/or modify it
  5. under the terms of the GNU General Public License as published by the
  6. Free Software Foundation; either version 3, or (at your option) any
  7. later version.
  8. GCC is distributed in the hope that it will be useful, but WITHOUT
  9. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  11. for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GCC; see the file COPYING3. If not see
  14. <http://www.gnu.org/licenses/>. */
  15. #include "config.h"
  16. #include "system.h"
  17. #include "coretypes.h"
  18. #include "tm.h"
  19. #include "hash-set.h"
  20. #include "machmode.h"
  21. #include "vec.h"
  22. #include "double-int.h"
  23. #include "input.h"
  24. #include "alias.h"
  25. #include "symtab.h"
  26. #include "wide-int.h"
  27. #include "inchash.h"
  28. #include "tree.h"
  29. #include "fold-const.h"
  30. #include "stor-layout.h"
  31. #include "tm_p.h"
  32. #include "predict.h"
  33. #include "hard-reg-set.h"
  34. #include "function.h"
  35. #include "dominance.h"
  36. #include "cfg.h"
  37. #include "basic-block.h"
  38. #include "tree-pretty-print.h"
  39. #include "tree-ssa-alias.h"
  40. #include "internal-fn.h"
  41. #include "gimple-expr.h"
  42. #include "is-a.h"
  43. #include "gimple.h"
  44. #include "gimplify.h"
  45. #include "gimple-iterator.h"
  46. #include "gimplify-me.h"
  47. #include "gimple-ssa.h"
  48. #include "tree-ssa-loop-ivopts.h"
  49. #include "tree-ssa-loop-manip.h"
  50. #include "tree-ssa-loop-niter.h"
  51. #include "tree-ssa-loop.h"
  52. #include "tree-into-ssa.h"
  53. #include "cfgloop.h"
  54. #include "tree-pass.h"
  55. #include "insn-config.h"
  56. #include "tree-chrec.h"
  57. #include "tree-scalar-evolution.h"
  58. #include "diagnostic-core.h"
  59. #include "params.h"
  60. #include "langhooks.h"
  61. #include "tree-inline.h"
  62. #include "tree-data-ref.h"
  63. /* FIXME: Needed for optabs, but this should all be moved to a TBD interface
  64. between the GIMPLE and RTL worlds. */
  65. #include "hashtab.h"
  66. #include "rtl.h"
  67. #include "flags.h"
  68. #include "statistics.h"
  69. #include "real.h"
  70. #include "fixed-value.h"
  71. #include "expmed.h"
  72. #include "dojump.h"
  73. #include "explow.h"
  74. #include "calls.h"
  75. #include "emit-rtl.h"
  76. #include "varasm.h"
  77. #include "stmt.h"
  78. #include "expr.h"
  79. #include "insn-codes.h"
  80. #include "optabs.h"
  81. #include "recog.h"
  82. /* This pass inserts prefetch instructions to optimize cache usage during
  83. accesses to arrays in loops. It processes loops sequentially and:
  84. 1) Gathers all memory references in the single loop.
  85. 2) For each of the references it decides when it is profitable to prefetch
  86. it. To do it, we evaluate the reuse among the accesses, and determines
  87. two values: PREFETCH_BEFORE (meaning that it only makes sense to do
  88. prefetching in the first PREFETCH_BEFORE iterations of the loop) and
  89. PREFETCH_MOD (meaning that it only makes sense to prefetch in the
  90. iterations of the loop that are zero modulo PREFETCH_MOD). For example
  91. (assuming cache line size is 64 bytes, char has size 1 byte and there
  92. is no hardware sequential prefetch):
  93. char *a;
  94. for (i = 0; i < max; i++)
  95. {
  96. a[255] = ...; (0)
  97. a[i] = ...; (1)
  98. a[i + 64] = ...; (2)
  99. a[16*i] = ...; (3)
  100. a[187*i] = ...; (4)
  101. a[187*i + 50] = ...; (5)
  102. }
  103. (0) obviously has PREFETCH_BEFORE 1
  104. (1) has PREFETCH_BEFORE 64, since (2) accesses the same memory
  105. location 64 iterations before it, and PREFETCH_MOD 64 (since
  106. it hits the same cache line otherwise).
  107. (2) has PREFETCH_MOD 64
  108. (3) has PREFETCH_MOD 4
  109. (4) has PREFETCH_MOD 1. We do not set PREFETCH_BEFORE here, since
  110. the cache line accessed by (5) is the same with probability only
  111. 7/32.
  112. (5) has PREFETCH_MOD 1 as well.
  113. Additionally, we use data dependence analysis to determine for each
  114. reference the distance till the first reuse; this information is used
  115. to determine the temporality of the issued prefetch instruction.
  116. 3) We determine how much ahead we need to prefetch. The number of
  117. iterations needed is time to fetch / time spent in one iteration of
  118. the loop. The problem is that we do not know either of these values,
  119. so we just make a heuristic guess based on a magic (possibly)
  120. target-specific constant and size of the loop.
  121. 4) Determine which of the references we prefetch. We take into account
  122. that there is a maximum number of simultaneous prefetches (provided
  123. by machine description). We prefetch as many prefetches as possible
  124. while still within this bound (starting with those with lowest
  125. prefetch_mod, since they are responsible for most of the cache
  126. misses).
  127. 5) We unroll and peel loops so that we are able to satisfy PREFETCH_MOD
  128. and PREFETCH_BEFORE requirements (within some bounds), and to avoid
  129. prefetching nonaccessed memory.
  130. TODO -- actually implement peeling.
  131. 6) We actually emit the prefetch instructions. ??? Perhaps emit the
  132. prefetch instructions with guards in cases where 5) was not sufficient
  133. to satisfy the constraints?
  134. A cost model is implemented to determine whether or not prefetching is
  135. profitable for a given loop. The cost model has three heuristics:
  136. 1. Function trip_count_to_ahead_ratio_too_small_p implements a
  137. heuristic that determines whether or not the loop has too few
  138. iterations (compared to ahead). Prefetching is not likely to be
  139. beneficial if the trip count to ahead ratio is below a certain
  140. minimum.
  141. 2. Function mem_ref_count_reasonable_p implements a heuristic that
  142. determines whether the given loop has enough CPU ops that can be
  143. overlapped with cache missing memory ops. If not, the loop
  144. won't benefit from prefetching. In the implementation,
  145. prefetching is not considered beneficial if the ratio between
  146. the instruction count and the mem ref count is below a certain
  147. minimum.
  148. 3. Function insn_to_prefetch_ratio_too_small_p implements a
  149. heuristic that disables prefetching in a loop if the prefetching
  150. cost is above a certain limit. The relative prefetching cost is
  151. estimated by taking the ratio between the prefetch count and the
  152. total intruction count (this models the I-cache cost).
  153. The limits used in these heuristics are defined as parameters with
  154. reasonable default values. Machine-specific default values will be
  155. added later.
  156. Some other TODO:
  157. -- write and use more general reuse analysis (that could be also used
  158. in other cache aimed loop optimizations)
  159. -- make it behave sanely together with the prefetches given by user
  160. (now we just ignore them; at the very least we should avoid
  161. optimizing loops in that user put his own prefetches)
  162. -- we assume cache line size alignment of arrays; this could be
  163. improved. */
  164. /* Magic constants follow. These should be replaced by machine specific
  165. numbers. */
  166. /* True if write can be prefetched by a read prefetch. */
  167. #ifndef WRITE_CAN_USE_READ_PREFETCH
  168. #define WRITE_CAN_USE_READ_PREFETCH 1
  169. #endif
  170. /* True if read can be prefetched by a write prefetch. */
  171. #ifndef READ_CAN_USE_WRITE_PREFETCH
  172. #define READ_CAN_USE_WRITE_PREFETCH 0
  173. #endif
  174. /* The size of the block loaded by a single prefetch. Usually, this is
  175. the same as cache line size (at the moment, we only consider one level
  176. of cache hierarchy). */
  177. #ifndef PREFETCH_BLOCK
  178. #define PREFETCH_BLOCK L1_CACHE_LINE_SIZE
  179. #endif
  180. /* Do we have a forward hardware sequential prefetching? */
  181. #ifndef HAVE_FORWARD_PREFETCH
  182. #define HAVE_FORWARD_PREFETCH 0
  183. #endif
  184. /* Do we have a backward hardware sequential prefetching? */
  185. #ifndef HAVE_BACKWARD_PREFETCH
  186. #define HAVE_BACKWARD_PREFETCH 0
  187. #endif
  188. /* In some cases we are only able to determine that there is a certain
  189. probability that the two accesses hit the same cache line. In this
  190. case, we issue the prefetches for both of them if this probability
  191. is less then (1000 - ACCEPTABLE_MISS_RATE) per thousand. */
  192. #ifndef ACCEPTABLE_MISS_RATE
  193. #define ACCEPTABLE_MISS_RATE 50
  194. #endif
  195. #ifndef HAVE_prefetch
  196. #define HAVE_prefetch 0
  197. #endif
  198. #define L1_CACHE_SIZE_BYTES ((unsigned) (L1_CACHE_SIZE * 1024))
  199. #define L2_CACHE_SIZE_BYTES ((unsigned) (L2_CACHE_SIZE * 1024))
  200. /* We consider a memory access nontemporal if it is not reused sooner than
  201. after L2_CACHE_SIZE_BYTES of memory are accessed. However, we ignore
  202. accesses closer than L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION,
  203. so that we use nontemporal prefetches e.g. if single memory location
  204. is accessed several times in a single iteration of the loop. */
  205. #define NONTEMPORAL_FRACTION 16
  206. /* In case we have to emit a memory fence instruction after the loop that
  207. uses nontemporal stores, this defines the builtin to use. */
  208. #ifndef FENCE_FOLLOWING_MOVNT
  209. #define FENCE_FOLLOWING_MOVNT NULL_TREE
  210. #endif
  211. /* It is not profitable to prefetch when the trip count is not at
  212. least TRIP_COUNT_TO_AHEAD_RATIO times the prefetch ahead distance.
  213. For example, in a loop with a prefetch ahead distance of 10,
  214. supposing that TRIP_COUNT_TO_AHEAD_RATIO is equal to 4, it is
  215. profitable to prefetch when the trip count is greater or equal to
  216. 40. In that case, 30 out of the 40 iterations will benefit from
  217. prefetching. */
  218. #ifndef TRIP_COUNT_TO_AHEAD_RATIO
  219. #define TRIP_COUNT_TO_AHEAD_RATIO 4
  220. #endif
  221. /* The group of references between that reuse may occur. */
  222. struct mem_ref_group
  223. {
  224. tree base; /* Base of the reference. */
  225. tree step; /* Step of the reference. */
  226. struct mem_ref *refs; /* References in the group. */
  227. struct mem_ref_group *next; /* Next group of references. */
  228. };
  229. /* Assigned to PREFETCH_BEFORE when all iterations are to be prefetched. */
  230. #define PREFETCH_ALL (~(unsigned HOST_WIDE_INT) 0)
  231. /* Do not generate a prefetch if the unroll factor is significantly less
  232. than what is required by the prefetch. This is to avoid redundant
  233. prefetches. For example, when prefetch_mod is 16 and unroll_factor is
  234. 2, prefetching requires unrolling the loop 16 times, but
  235. the loop is actually unrolled twice. In this case (ratio = 8),
  236. prefetching is not likely to be beneficial. */
  237. #ifndef PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO
  238. #define PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO 4
  239. #endif
  240. /* Some of the prefetch computations have quadratic complexity. We want to
  241. avoid huge compile times and, therefore, want to limit the amount of
  242. memory references per loop where we consider prefetching. */
  243. #ifndef PREFETCH_MAX_MEM_REFS_PER_LOOP
  244. #define PREFETCH_MAX_MEM_REFS_PER_LOOP 200
  245. #endif
  246. /* The memory reference. */
  247. struct mem_ref
  248. {
  249. gimple stmt; /* Statement in that the reference appears. */
  250. tree mem; /* The reference. */
  251. HOST_WIDE_INT delta; /* Constant offset of the reference. */
  252. struct mem_ref_group *group; /* The group of references it belongs to. */
  253. unsigned HOST_WIDE_INT prefetch_mod;
  254. /* Prefetch only each PREFETCH_MOD-th
  255. iteration. */
  256. unsigned HOST_WIDE_INT prefetch_before;
  257. /* Prefetch only first PREFETCH_BEFORE
  258. iterations. */
  259. unsigned reuse_distance; /* The amount of data accessed before the first
  260. reuse of this value. */
  261. struct mem_ref *next; /* The next reference in the group. */
  262. unsigned write_p : 1; /* Is it a write? */
  263. unsigned independent_p : 1; /* True if the reference is independent on
  264. all other references inside the loop. */
  265. unsigned issue_prefetch_p : 1; /* Should we really issue the prefetch? */
  266. unsigned storent_p : 1; /* True if we changed the store to a
  267. nontemporal one. */
  268. };
  269. /* Dumps information about memory reference */
  270. static void
  271. dump_mem_details (FILE *file, tree base, tree step,
  272. HOST_WIDE_INT delta, bool write_p)
  273. {
  274. fprintf (file, "(base ");
  275. print_generic_expr (file, base, TDF_SLIM);
  276. fprintf (file, ", step ");
  277. if (cst_and_fits_in_hwi (step))
  278. fprintf (file, HOST_WIDE_INT_PRINT_DEC, int_cst_value (step));
  279. else
  280. print_generic_expr (file, step, TDF_TREE);
  281. fprintf (file, ")\n");
  282. fprintf (file, " delta ");
  283. fprintf (file, HOST_WIDE_INT_PRINT_DEC, delta);
  284. fprintf (file, "\n");
  285. fprintf (file, " %s\n", write_p ? "write" : "read");
  286. fprintf (file, "\n");
  287. }
  288. /* Dumps information about reference REF to FILE. */
  289. static void
  290. dump_mem_ref (FILE *file, struct mem_ref *ref)
  291. {
  292. fprintf (file, "Reference %p:\n", (void *) ref);
  293. fprintf (file, " group %p ", (void *) ref->group);
  294. dump_mem_details (file, ref->group->base, ref->group->step, ref->delta,
  295. ref->write_p);
  296. }
  297. /* Finds a group with BASE and STEP in GROUPS, or creates one if it does not
  298. exist. */
  299. static struct mem_ref_group *
  300. find_or_create_group (struct mem_ref_group **groups, tree base, tree step)
  301. {
  302. struct mem_ref_group *group;
  303. for (; *groups; groups = &(*groups)->next)
  304. {
  305. if (operand_equal_p ((*groups)->step, step, 0)
  306. && operand_equal_p ((*groups)->base, base, 0))
  307. return *groups;
  308. /* If step is an integer constant, keep the list of groups sorted
  309. by decreasing step. */
  310. if (cst_and_fits_in_hwi ((*groups)->step) && cst_and_fits_in_hwi (step)
  311. && int_cst_value ((*groups)->step) < int_cst_value (step))
  312. break;
  313. }
  314. group = XNEW (struct mem_ref_group);
  315. group->base = base;
  316. group->step = step;
  317. group->refs = NULL;
  318. group->next = *groups;
  319. *groups = group;
  320. return group;
  321. }
  322. /* Records a memory reference MEM in GROUP with offset DELTA and write status
  323. WRITE_P. The reference occurs in statement STMT. */
  324. static void
  325. record_ref (struct mem_ref_group *group, gimple stmt, tree mem,
  326. HOST_WIDE_INT delta, bool write_p)
  327. {
  328. struct mem_ref **aref;
  329. /* Do not record the same address twice. */
  330. for (aref = &group->refs; *aref; aref = &(*aref)->next)
  331. {
  332. /* It does not have to be possible for write reference to reuse the read
  333. prefetch, or vice versa. */
  334. if (!WRITE_CAN_USE_READ_PREFETCH
  335. && write_p
  336. && !(*aref)->write_p)
  337. continue;
  338. if (!READ_CAN_USE_WRITE_PREFETCH
  339. && !write_p
  340. && (*aref)->write_p)
  341. continue;
  342. if ((*aref)->delta == delta)
  343. return;
  344. }
  345. (*aref) = XNEW (struct mem_ref);
  346. (*aref)->stmt = stmt;
  347. (*aref)->mem = mem;
  348. (*aref)->delta = delta;
  349. (*aref)->write_p = write_p;
  350. (*aref)->prefetch_before = PREFETCH_ALL;
  351. (*aref)->prefetch_mod = 1;
  352. (*aref)->reuse_distance = 0;
  353. (*aref)->issue_prefetch_p = false;
  354. (*aref)->group = group;
  355. (*aref)->next = NULL;
  356. (*aref)->independent_p = false;
  357. (*aref)->storent_p = false;
  358. if (dump_file && (dump_flags & TDF_DETAILS))
  359. dump_mem_ref (dump_file, *aref);
  360. }
  361. /* Release memory references in GROUPS. */
  362. static void
  363. release_mem_refs (struct mem_ref_group *groups)
  364. {
  365. struct mem_ref_group *next_g;
  366. struct mem_ref *ref, *next_r;
  367. for (; groups; groups = next_g)
  368. {
  369. next_g = groups->next;
  370. for (ref = groups->refs; ref; ref = next_r)
  371. {
  372. next_r = ref->next;
  373. free (ref);
  374. }
  375. free (groups);
  376. }
  377. }
  378. /* A structure used to pass arguments to idx_analyze_ref. */
  379. struct ar_data
  380. {
  381. struct loop *loop; /* Loop of the reference. */
  382. gimple stmt; /* Statement of the reference. */
  383. tree *step; /* Step of the memory reference. */
  384. HOST_WIDE_INT *delta; /* Offset of the memory reference. */
  385. };
  386. /* Analyzes a single INDEX of a memory reference to obtain information
  387. described at analyze_ref. Callback for for_each_index. */
  388. static bool
  389. idx_analyze_ref (tree base, tree *index, void *data)
  390. {
  391. struct ar_data *ar_data = (struct ar_data *) data;
  392. tree ibase, step, stepsize;
  393. HOST_WIDE_INT idelta = 0, imult = 1;
  394. affine_iv iv;
  395. if (!simple_iv (ar_data->loop, loop_containing_stmt (ar_data->stmt),
  396. *index, &iv, true))
  397. return false;
  398. ibase = iv.base;
  399. step = iv.step;
  400. if (TREE_CODE (ibase) == POINTER_PLUS_EXPR
  401. && cst_and_fits_in_hwi (TREE_OPERAND (ibase, 1)))
  402. {
  403. idelta = int_cst_value (TREE_OPERAND (ibase, 1));
  404. ibase = TREE_OPERAND (ibase, 0);
  405. }
  406. if (cst_and_fits_in_hwi (ibase))
  407. {
  408. idelta += int_cst_value (ibase);
  409. ibase = build_int_cst (TREE_TYPE (ibase), 0);
  410. }
  411. if (TREE_CODE (base) == ARRAY_REF)
  412. {
  413. stepsize = array_ref_element_size (base);
  414. if (!cst_and_fits_in_hwi (stepsize))
  415. return false;
  416. imult = int_cst_value (stepsize);
  417. step = fold_build2 (MULT_EXPR, sizetype,
  418. fold_convert (sizetype, step),
  419. fold_convert (sizetype, stepsize));
  420. idelta *= imult;
  421. }
  422. if (*ar_data->step == NULL_TREE)
  423. *ar_data->step = step;
  424. else
  425. *ar_data->step = fold_build2 (PLUS_EXPR, sizetype,
  426. fold_convert (sizetype, *ar_data->step),
  427. fold_convert (sizetype, step));
  428. *ar_data->delta += idelta;
  429. *index = ibase;
  430. return true;
  431. }
  432. /* Tries to express REF_P in shape &BASE + STEP * iter + DELTA, where DELTA and
  433. STEP are integer constants and iter is number of iterations of LOOP. The
  434. reference occurs in statement STMT. Strips nonaddressable component
  435. references from REF_P. */
  436. static bool
  437. analyze_ref (struct loop *loop, tree *ref_p, tree *base,
  438. tree *step, HOST_WIDE_INT *delta,
  439. gimple stmt)
  440. {
  441. struct ar_data ar_data;
  442. tree off;
  443. HOST_WIDE_INT bit_offset;
  444. tree ref = *ref_p;
  445. *step = NULL_TREE;
  446. *delta = 0;
  447. /* First strip off the component references. Ignore bitfields.
  448. Also strip off the real and imagine parts of a complex, so that
  449. they can have the same base. */
  450. if (TREE_CODE (ref) == REALPART_EXPR
  451. || TREE_CODE (ref) == IMAGPART_EXPR
  452. || (TREE_CODE (ref) == COMPONENT_REF
  453. && DECL_NONADDRESSABLE_P (TREE_OPERAND (ref, 1))))
  454. {
  455. if (TREE_CODE (ref) == IMAGPART_EXPR)
  456. *delta += int_size_in_bytes (TREE_TYPE (ref));
  457. ref = TREE_OPERAND (ref, 0);
  458. }
  459. *ref_p = ref;
  460. for (; TREE_CODE (ref) == COMPONENT_REF; ref = TREE_OPERAND (ref, 0))
  461. {
  462. off = DECL_FIELD_BIT_OFFSET (TREE_OPERAND (ref, 1));
  463. bit_offset = TREE_INT_CST_LOW (off);
  464. gcc_assert (bit_offset % BITS_PER_UNIT == 0);
  465. *delta += bit_offset / BITS_PER_UNIT;
  466. }
  467. *base = unshare_expr (ref);
  468. ar_data.loop = loop;
  469. ar_data.stmt = stmt;
  470. ar_data.step = step;
  471. ar_data.delta = delta;
  472. return for_each_index (base, idx_analyze_ref, &ar_data);
  473. }
  474. /* Record a memory reference REF to the list REFS. The reference occurs in
  475. LOOP in statement STMT and it is write if WRITE_P. Returns true if the
  476. reference was recorded, false otherwise. */
  477. static bool
  478. gather_memory_references_ref (struct loop *loop, struct mem_ref_group **refs,
  479. tree ref, bool write_p, gimple stmt)
  480. {
  481. tree base, step;
  482. HOST_WIDE_INT delta;
  483. struct mem_ref_group *agrp;
  484. if (get_base_address (ref) == NULL)
  485. return false;
  486. if (!analyze_ref (loop, &ref, &base, &step, &delta, stmt))
  487. return false;
  488. /* If analyze_ref fails the default is a NULL_TREE. We can stop here. */
  489. if (step == NULL_TREE)
  490. return false;
  491. /* Stop if the address of BASE could not be taken. */
  492. if (may_be_nonaddressable_p (base))
  493. return false;
  494. /* Limit non-constant step prefetching only to the innermost loops and
  495. only when the step is loop invariant in the entire loop nest. */
  496. if (!cst_and_fits_in_hwi (step))
  497. {
  498. if (loop->inner != NULL)
  499. {
  500. if (dump_file && (dump_flags & TDF_DETAILS))
  501. {
  502. fprintf (dump_file, "Memory expression %p\n",(void *) ref );
  503. print_generic_expr (dump_file, ref, TDF_TREE);
  504. fprintf (dump_file,":");
  505. dump_mem_details (dump_file, base, step, delta, write_p);
  506. fprintf (dump_file,
  507. "Ignoring %p, non-constant step prefetching is "
  508. "limited to inner most loops \n",
  509. (void *) ref);
  510. }
  511. return false;
  512. }
  513. else
  514. {
  515. if (!expr_invariant_in_loop_p (loop_outermost (loop), step))
  516. {
  517. if (dump_file && (dump_flags & TDF_DETAILS))
  518. {
  519. fprintf (dump_file, "Memory expression %p\n",(void *) ref );
  520. print_generic_expr (dump_file, ref, TDF_TREE);
  521. fprintf (dump_file,":");
  522. dump_mem_details (dump_file, base, step, delta, write_p);
  523. fprintf (dump_file,
  524. "Not prefetching, ignoring %p due to "
  525. "loop variant step\n",
  526. (void *) ref);
  527. }
  528. return false;
  529. }
  530. }
  531. }
  532. /* Now we know that REF = &BASE + STEP * iter + DELTA, where DELTA and STEP
  533. are integer constants. */
  534. agrp = find_or_create_group (refs, base, step);
  535. record_ref (agrp, stmt, ref, delta, write_p);
  536. return true;
  537. }
  538. /* Record the suitable memory references in LOOP. NO_OTHER_REFS is set to
  539. true if there are no other memory references inside the loop. */
  540. static struct mem_ref_group *
  541. gather_memory_references (struct loop *loop, bool *no_other_refs, unsigned *ref_count)
  542. {
  543. basic_block *body = get_loop_body_in_dom_order (loop);
  544. basic_block bb;
  545. unsigned i;
  546. gimple_stmt_iterator bsi;
  547. gimple stmt;
  548. tree lhs, rhs;
  549. struct mem_ref_group *refs = NULL;
  550. *no_other_refs = true;
  551. *ref_count = 0;
  552. /* Scan the loop body in order, so that the former references precede the
  553. later ones. */
  554. for (i = 0; i < loop->num_nodes; i++)
  555. {
  556. bb = body[i];
  557. if (bb->loop_father != loop)
  558. continue;
  559. for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
  560. {
  561. stmt = gsi_stmt (bsi);
  562. if (gimple_code (stmt) != GIMPLE_ASSIGN)
  563. {
  564. if (gimple_vuse (stmt)
  565. || (is_gimple_call (stmt)
  566. && !(gimple_call_flags (stmt) & ECF_CONST)))
  567. *no_other_refs = false;
  568. continue;
  569. }
  570. lhs = gimple_assign_lhs (stmt);
  571. rhs = gimple_assign_rhs1 (stmt);
  572. if (REFERENCE_CLASS_P (rhs))
  573. {
  574. *no_other_refs &= gather_memory_references_ref (loop, &refs,
  575. rhs, false, stmt);
  576. *ref_count += 1;
  577. }
  578. if (REFERENCE_CLASS_P (lhs))
  579. {
  580. *no_other_refs &= gather_memory_references_ref (loop, &refs,
  581. lhs, true, stmt);
  582. *ref_count += 1;
  583. }
  584. }
  585. }
  586. free (body);
  587. return refs;
  588. }
  589. /* Prune the prefetch candidate REF using the self-reuse. */
  590. static void
  591. prune_ref_by_self_reuse (struct mem_ref *ref)
  592. {
  593. HOST_WIDE_INT step;
  594. bool backward;
  595. /* If the step size is non constant, we cannot calculate prefetch_mod. */
  596. if (!cst_and_fits_in_hwi (ref->group->step))
  597. return;
  598. step = int_cst_value (ref->group->step);
  599. backward = step < 0;
  600. if (step == 0)
  601. {
  602. /* Prefetch references to invariant address just once. */
  603. ref->prefetch_before = 1;
  604. return;
  605. }
  606. if (backward)
  607. step = -step;
  608. if (step > PREFETCH_BLOCK)
  609. return;
  610. if ((backward && HAVE_BACKWARD_PREFETCH)
  611. || (!backward && HAVE_FORWARD_PREFETCH))
  612. {
  613. ref->prefetch_before = 1;
  614. return;
  615. }
  616. ref->prefetch_mod = PREFETCH_BLOCK / step;
  617. }
  618. /* Divides X by BY, rounding down. */
  619. static HOST_WIDE_INT
  620. ddown (HOST_WIDE_INT x, unsigned HOST_WIDE_INT by)
  621. {
  622. gcc_assert (by > 0);
  623. if (x >= 0)
  624. return x / by;
  625. else
  626. return (x + by - 1) / by;
  627. }
  628. /* Given a CACHE_LINE_SIZE and two inductive memory references
  629. with a common STEP greater than CACHE_LINE_SIZE and an address
  630. difference DELTA, compute the probability that they will fall
  631. in different cache lines. Return true if the computed miss rate
  632. is not greater than the ACCEPTABLE_MISS_RATE. DISTINCT_ITERS is the
  633. number of distinct iterations after which the pattern repeats itself.
  634. ALIGN_UNIT is the unit of alignment in bytes. */
  635. static bool
  636. is_miss_rate_acceptable (unsigned HOST_WIDE_INT cache_line_size,
  637. HOST_WIDE_INT step, HOST_WIDE_INT delta,
  638. unsigned HOST_WIDE_INT distinct_iters,
  639. int align_unit)
  640. {
  641. unsigned align, iter;
  642. int total_positions, miss_positions, max_allowed_miss_positions;
  643. int address1, address2, cache_line1, cache_line2;
  644. /* It always misses if delta is greater than or equal to the cache
  645. line size. */
  646. if (delta >= (HOST_WIDE_INT) cache_line_size)
  647. return false;
  648. miss_positions = 0;
  649. total_positions = (cache_line_size / align_unit) * distinct_iters;
  650. max_allowed_miss_positions = (ACCEPTABLE_MISS_RATE * total_positions) / 1000;
  651. /* Iterate through all possible alignments of the first
  652. memory reference within its cache line. */
  653. for (align = 0; align < cache_line_size; align += align_unit)
  654. /* Iterate through all distinct iterations. */
  655. for (iter = 0; iter < distinct_iters; iter++)
  656. {
  657. address1 = align + step * iter;
  658. address2 = address1 + delta;
  659. cache_line1 = address1 / cache_line_size;
  660. cache_line2 = address2 / cache_line_size;
  661. if (cache_line1 != cache_line2)
  662. {
  663. miss_positions += 1;
  664. if (miss_positions > max_allowed_miss_positions)
  665. return false;
  666. }
  667. }
  668. return true;
  669. }
  670. /* Prune the prefetch candidate REF using the reuse with BY.
  671. If BY_IS_BEFORE is true, BY is before REF in the loop. */
  672. static void
  673. prune_ref_by_group_reuse (struct mem_ref *ref, struct mem_ref *by,
  674. bool by_is_before)
  675. {
  676. HOST_WIDE_INT step;
  677. bool backward;
  678. HOST_WIDE_INT delta_r = ref->delta, delta_b = by->delta;
  679. HOST_WIDE_INT delta = delta_b - delta_r;
  680. HOST_WIDE_INT hit_from;
  681. unsigned HOST_WIDE_INT prefetch_before, prefetch_block;
  682. HOST_WIDE_INT reduced_step;
  683. unsigned HOST_WIDE_INT reduced_prefetch_block;
  684. tree ref_type;
  685. int align_unit;
  686. /* If the step is non constant we cannot calculate prefetch_before. */
  687. if (!cst_and_fits_in_hwi (ref->group->step)) {
  688. return;
  689. }
  690. step = int_cst_value (ref->group->step);
  691. backward = step < 0;
  692. if (delta == 0)
  693. {
  694. /* If the references has the same address, only prefetch the
  695. former. */
  696. if (by_is_before)
  697. ref->prefetch_before = 0;
  698. return;
  699. }
  700. if (!step)
  701. {
  702. /* If the reference addresses are invariant and fall into the
  703. same cache line, prefetch just the first one. */
  704. if (!by_is_before)
  705. return;
  706. if (ddown (ref->delta, PREFETCH_BLOCK)
  707. != ddown (by->delta, PREFETCH_BLOCK))
  708. return;
  709. ref->prefetch_before = 0;
  710. return;
  711. }
  712. /* Only prune the reference that is behind in the array. */
  713. if (backward)
  714. {
  715. if (delta > 0)
  716. return;
  717. /* Transform the data so that we may assume that the accesses
  718. are forward. */
  719. delta = - delta;
  720. step = -step;
  721. delta_r = PREFETCH_BLOCK - 1 - delta_r;
  722. delta_b = PREFETCH_BLOCK - 1 - delta_b;
  723. }
  724. else
  725. {
  726. if (delta < 0)
  727. return;
  728. }
  729. /* Check whether the two references are likely to hit the same cache
  730. line, and how distant the iterations in that it occurs are from
  731. each other. */
  732. if (step <= PREFETCH_BLOCK)
  733. {
  734. /* The accesses are sure to meet. Let us check when. */
  735. hit_from = ddown (delta_b, PREFETCH_BLOCK) * PREFETCH_BLOCK;
  736. prefetch_before = (hit_from - delta_r + step - 1) / step;
  737. /* Do not reduce prefetch_before if we meet beyond cache size. */
  738. if (prefetch_before > absu_hwi (L2_CACHE_SIZE_BYTES / step))
  739. prefetch_before = PREFETCH_ALL;
  740. if (prefetch_before < ref->prefetch_before)
  741. ref->prefetch_before = prefetch_before;
  742. return;
  743. }
  744. /* A more complicated case with step > prefetch_block. First reduce
  745. the ratio between the step and the cache line size to its simplest
  746. terms. The resulting denominator will then represent the number of
  747. distinct iterations after which each address will go back to its
  748. initial location within the cache line. This computation assumes
  749. that PREFETCH_BLOCK is a power of two. */
  750. prefetch_block = PREFETCH_BLOCK;
  751. reduced_prefetch_block = prefetch_block;
  752. reduced_step = step;
  753. while ((reduced_step & 1) == 0
  754. && reduced_prefetch_block > 1)
  755. {
  756. reduced_step >>= 1;
  757. reduced_prefetch_block >>= 1;
  758. }
  759. prefetch_before = delta / step;
  760. delta %= step;
  761. ref_type = TREE_TYPE (ref->mem);
  762. align_unit = TYPE_ALIGN (ref_type) / 8;
  763. if (is_miss_rate_acceptable (prefetch_block, step, delta,
  764. reduced_prefetch_block, align_unit))
  765. {
  766. /* Do not reduce prefetch_before if we meet beyond cache size. */
  767. if (prefetch_before > L2_CACHE_SIZE_BYTES / PREFETCH_BLOCK)
  768. prefetch_before = PREFETCH_ALL;
  769. if (prefetch_before < ref->prefetch_before)
  770. ref->prefetch_before = prefetch_before;
  771. return;
  772. }
  773. /* Try also the following iteration. */
  774. prefetch_before++;
  775. delta = step - delta;
  776. if (is_miss_rate_acceptable (prefetch_block, step, delta,
  777. reduced_prefetch_block, align_unit))
  778. {
  779. if (prefetch_before < ref->prefetch_before)
  780. ref->prefetch_before = prefetch_before;
  781. return;
  782. }
  783. /* The ref probably does not reuse by. */
  784. return;
  785. }
  786. /* Prune the prefetch candidate REF using the reuses with other references
  787. in REFS. */
  788. static void
  789. prune_ref_by_reuse (struct mem_ref *ref, struct mem_ref *refs)
  790. {
  791. struct mem_ref *prune_by;
  792. bool before = true;
  793. prune_ref_by_self_reuse (ref);
  794. for (prune_by = refs; prune_by; prune_by = prune_by->next)
  795. {
  796. if (prune_by == ref)
  797. {
  798. before = false;
  799. continue;
  800. }
  801. if (!WRITE_CAN_USE_READ_PREFETCH
  802. && ref->write_p
  803. && !prune_by->write_p)
  804. continue;
  805. if (!READ_CAN_USE_WRITE_PREFETCH
  806. && !ref->write_p
  807. && prune_by->write_p)
  808. continue;
  809. prune_ref_by_group_reuse (ref, prune_by, before);
  810. }
  811. }
  812. /* Prune the prefetch candidates in GROUP using the reuse analysis. */
  813. static void
  814. prune_group_by_reuse (struct mem_ref_group *group)
  815. {
  816. struct mem_ref *ref_pruned;
  817. for (ref_pruned = group->refs; ref_pruned; ref_pruned = ref_pruned->next)
  818. {
  819. prune_ref_by_reuse (ref_pruned, group->refs);
  820. if (dump_file && (dump_flags & TDF_DETAILS))
  821. {
  822. fprintf (dump_file, "Reference %p:", (void *) ref_pruned);
  823. if (ref_pruned->prefetch_before == PREFETCH_ALL
  824. && ref_pruned->prefetch_mod == 1)
  825. fprintf (dump_file, " no restrictions");
  826. else if (ref_pruned->prefetch_before == 0)
  827. fprintf (dump_file, " do not prefetch");
  828. else if (ref_pruned->prefetch_before <= ref_pruned->prefetch_mod)
  829. fprintf (dump_file, " prefetch once");
  830. else
  831. {
  832. if (ref_pruned->prefetch_before != PREFETCH_ALL)
  833. {
  834. fprintf (dump_file, " prefetch before ");
  835. fprintf (dump_file, HOST_WIDE_INT_PRINT_DEC,
  836. ref_pruned->prefetch_before);
  837. }
  838. if (ref_pruned->prefetch_mod != 1)
  839. {
  840. fprintf (dump_file, " prefetch mod ");
  841. fprintf (dump_file, HOST_WIDE_INT_PRINT_DEC,
  842. ref_pruned->prefetch_mod);
  843. }
  844. }
  845. fprintf (dump_file, "\n");
  846. }
  847. }
  848. }
  849. /* Prune the list of prefetch candidates GROUPS using the reuse analysis. */
  850. static void
  851. prune_by_reuse (struct mem_ref_group *groups)
  852. {
  853. for (; groups; groups = groups->next)
  854. prune_group_by_reuse (groups);
  855. }
  856. /* Returns true if we should issue prefetch for REF. */
  857. static bool
  858. should_issue_prefetch_p (struct mem_ref *ref)
  859. {
  860. /* For now do not issue prefetches for only first few of the
  861. iterations. */
  862. if (ref->prefetch_before != PREFETCH_ALL)
  863. {
  864. if (dump_file && (dump_flags & TDF_DETAILS))
  865. fprintf (dump_file, "Ignoring %p due to prefetch_before\n",
  866. (void *) ref);
  867. return false;
  868. }
  869. /* Do not prefetch nontemporal stores. */
  870. if (ref->storent_p)
  871. {
  872. if (dump_file && (dump_flags & TDF_DETAILS))
  873. fprintf (dump_file, "Ignoring nontemporal store %p\n", (void *) ref);
  874. return false;
  875. }
  876. return true;
  877. }
  878. /* Decide which of the prefetch candidates in GROUPS to prefetch.
  879. AHEAD is the number of iterations to prefetch ahead (which corresponds
  880. to the number of simultaneous instances of one prefetch running at a
  881. time). UNROLL_FACTOR is the factor by that the loop is going to be
  882. unrolled. Returns true if there is anything to prefetch. */
  883. static bool
  884. schedule_prefetches (struct mem_ref_group *groups, unsigned unroll_factor,
  885. unsigned ahead)
  886. {
  887. unsigned remaining_prefetch_slots, n_prefetches, prefetch_slots;
  888. unsigned slots_per_prefetch;
  889. struct mem_ref *ref;
  890. bool any = false;
  891. /* At most SIMULTANEOUS_PREFETCHES should be running at the same time. */
  892. remaining_prefetch_slots = SIMULTANEOUS_PREFETCHES;
  893. /* The prefetch will run for AHEAD iterations of the original loop, i.e.,
  894. AHEAD / UNROLL_FACTOR iterations of the unrolled loop. In each iteration,
  895. it will need a prefetch slot. */
  896. slots_per_prefetch = (ahead + unroll_factor / 2) / unroll_factor;
  897. if (dump_file && (dump_flags & TDF_DETAILS))
  898. fprintf (dump_file, "Each prefetch instruction takes %u prefetch slots.\n",
  899. slots_per_prefetch);
  900. /* For now we just take memory references one by one and issue
  901. prefetches for as many as possible. The groups are sorted
  902. starting with the largest step, since the references with
  903. large step are more likely to cause many cache misses. */
  904. for (; groups; groups = groups->next)
  905. for (ref = groups->refs; ref; ref = ref->next)
  906. {
  907. if (!should_issue_prefetch_p (ref))
  908. continue;
  909. /* The loop is far from being sufficiently unrolled for this
  910. prefetch. Do not generate prefetch to avoid many redudant
  911. prefetches. */
  912. if (ref->prefetch_mod / unroll_factor > PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO)
  913. continue;
  914. /* If we need to prefetch the reference each PREFETCH_MOD iterations,
  915. and we unroll the loop UNROLL_FACTOR times, we need to insert
  916. ceil (UNROLL_FACTOR / PREFETCH_MOD) instructions in each
  917. iteration. */
  918. n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
  919. / ref->prefetch_mod);
  920. prefetch_slots = n_prefetches * slots_per_prefetch;
  921. /* If more than half of the prefetches would be lost anyway, do not
  922. issue the prefetch. */
  923. if (2 * remaining_prefetch_slots < prefetch_slots)
  924. continue;
  925. ref->issue_prefetch_p = true;
  926. if (remaining_prefetch_slots <= prefetch_slots)
  927. return true;
  928. remaining_prefetch_slots -= prefetch_slots;
  929. any = true;
  930. }
  931. return any;
  932. }
  933. /* Return TRUE if no prefetch is going to be generated in the given
  934. GROUPS. */
  935. static bool
  936. nothing_to_prefetch_p (struct mem_ref_group *groups)
  937. {
  938. struct mem_ref *ref;
  939. for (; groups; groups = groups->next)
  940. for (ref = groups->refs; ref; ref = ref->next)
  941. if (should_issue_prefetch_p (ref))
  942. return false;
  943. return true;
  944. }
  945. /* Estimate the number of prefetches in the given GROUPS.
  946. UNROLL_FACTOR is the factor by which LOOP was unrolled. */
  947. static int
  948. estimate_prefetch_count (struct mem_ref_group *groups, unsigned unroll_factor)
  949. {
  950. struct mem_ref *ref;
  951. unsigned n_prefetches;
  952. int prefetch_count = 0;
  953. for (; groups; groups = groups->next)
  954. for (ref = groups->refs; ref; ref = ref->next)
  955. if (should_issue_prefetch_p (ref))
  956. {
  957. n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
  958. / ref->prefetch_mod);
  959. prefetch_count += n_prefetches;
  960. }
  961. return prefetch_count;
  962. }
  963. /* Issue prefetches for the reference REF into loop as decided before.
  964. HEAD is the number of iterations to prefetch ahead. UNROLL_FACTOR
  965. is the factor by which LOOP was unrolled. */
  966. static void
  967. issue_prefetch_ref (struct mem_ref *ref, unsigned unroll_factor, unsigned ahead)
  968. {
  969. HOST_WIDE_INT delta;
  970. tree addr, addr_base, write_p, local, forward;
  971. gcall *prefetch;
  972. gimple_stmt_iterator bsi;
  973. unsigned n_prefetches, ap;
  974. bool nontemporal = ref->reuse_distance >= L2_CACHE_SIZE_BYTES;
  975. if (dump_file && (dump_flags & TDF_DETAILS))
  976. fprintf (dump_file, "Issued%s prefetch for %p.\n",
  977. nontemporal ? " nontemporal" : "",
  978. (void *) ref);
  979. bsi = gsi_for_stmt (ref->stmt);
  980. n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
  981. / ref->prefetch_mod);
  982. addr_base = build_fold_addr_expr_with_type (ref->mem, ptr_type_node);
  983. addr_base = force_gimple_operand_gsi (&bsi, unshare_expr (addr_base),
  984. true, NULL, true, GSI_SAME_STMT);
  985. write_p = ref->write_p ? integer_one_node : integer_zero_node;
  986. local = nontemporal ? integer_zero_node : integer_three_node;
  987. for (ap = 0; ap < n_prefetches; ap++)
  988. {
  989. if (cst_and_fits_in_hwi (ref->group->step))
  990. {
  991. /* Determine the address to prefetch. */
  992. delta = (ahead + ap * ref->prefetch_mod) *
  993. int_cst_value (ref->group->step);
  994. addr = fold_build_pointer_plus_hwi (addr_base, delta);
  995. addr = force_gimple_operand_gsi (&bsi, unshare_expr (addr), true, NULL,
  996. true, GSI_SAME_STMT);
  997. }
  998. else
  999. {
  1000. /* The step size is non-constant but loop-invariant. We use the
  1001. heuristic to simply prefetch ahead iterations ahead. */
  1002. forward = fold_build2 (MULT_EXPR, sizetype,
  1003. fold_convert (sizetype, ref->group->step),
  1004. fold_convert (sizetype, size_int (ahead)));
  1005. addr = fold_build_pointer_plus (addr_base, forward);
  1006. addr = force_gimple_operand_gsi (&bsi, unshare_expr (addr), true,
  1007. NULL, true, GSI_SAME_STMT);
  1008. }
  1009. /* Create the prefetch instruction. */
  1010. prefetch = gimple_build_call (builtin_decl_explicit (BUILT_IN_PREFETCH),
  1011. 3, addr, write_p, local);
  1012. gsi_insert_before (&bsi, prefetch, GSI_SAME_STMT);
  1013. }
  1014. }
  1015. /* Issue prefetches for the references in GROUPS into loop as decided before.
  1016. HEAD is the number of iterations to prefetch ahead. UNROLL_FACTOR is the
  1017. factor by that LOOP was unrolled. */
  1018. static void
  1019. issue_prefetches (struct mem_ref_group *groups,
  1020. unsigned unroll_factor, unsigned ahead)
  1021. {
  1022. struct mem_ref *ref;
  1023. for (; groups; groups = groups->next)
  1024. for (ref = groups->refs; ref; ref = ref->next)
  1025. if (ref->issue_prefetch_p)
  1026. issue_prefetch_ref (ref, unroll_factor, ahead);
  1027. }
  1028. /* Returns true if REF is a memory write for that a nontemporal store insn
  1029. can be used. */
  1030. static bool
  1031. nontemporal_store_p (struct mem_ref *ref)
  1032. {
  1033. machine_mode mode;
  1034. enum insn_code code;
  1035. /* REF must be a write that is not reused. We require it to be independent
  1036. on all other memory references in the loop, as the nontemporal stores may
  1037. be reordered with respect to other memory references. */
  1038. if (!ref->write_p
  1039. || !ref->independent_p
  1040. || ref->reuse_distance < L2_CACHE_SIZE_BYTES)
  1041. return false;
  1042. /* Check that we have the storent instruction for the mode. */
  1043. mode = TYPE_MODE (TREE_TYPE (ref->mem));
  1044. if (mode == BLKmode)
  1045. return false;
  1046. code = optab_handler (storent_optab, mode);
  1047. return code != CODE_FOR_nothing;
  1048. }
  1049. /* If REF is a nontemporal store, we mark the corresponding modify statement
  1050. and return true. Otherwise, we return false. */
  1051. static bool
  1052. mark_nontemporal_store (struct mem_ref *ref)
  1053. {
  1054. if (!nontemporal_store_p (ref))
  1055. return false;
  1056. if (dump_file && (dump_flags & TDF_DETAILS))
  1057. fprintf (dump_file, "Marked reference %p as a nontemporal store.\n",
  1058. (void *) ref);
  1059. gimple_assign_set_nontemporal_move (ref->stmt, true);
  1060. ref->storent_p = true;
  1061. return true;
  1062. }
  1063. /* Issue a memory fence instruction after LOOP. */
  1064. static void
  1065. emit_mfence_after_loop (struct loop *loop)
  1066. {
  1067. vec<edge> exits = get_loop_exit_edges (loop);
  1068. edge exit;
  1069. gcall *call;
  1070. gimple_stmt_iterator bsi;
  1071. unsigned i;
  1072. FOR_EACH_VEC_ELT (exits, i, exit)
  1073. {
  1074. call = gimple_build_call (FENCE_FOLLOWING_MOVNT, 0);
  1075. if (!single_pred_p (exit->dest)
  1076. /* If possible, we prefer not to insert the fence on other paths
  1077. in cfg. */
  1078. && !(exit->flags & EDGE_ABNORMAL))
  1079. split_loop_exit_edge (exit);
  1080. bsi = gsi_after_labels (exit->dest);
  1081. gsi_insert_before (&bsi, call, GSI_NEW_STMT);
  1082. }
  1083. exits.release ();
  1084. update_ssa (TODO_update_ssa_only_virtuals);
  1085. }
  1086. /* Returns true if we can use storent in loop, false otherwise. */
  1087. static bool
  1088. may_use_storent_in_loop_p (struct loop *loop)
  1089. {
  1090. bool ret = true;
  1091. if (loop->inner != NULL)
  1092. return false;
  1093. /* If we must issue a mfence insn after using storent, check that there
  1094. is a suitable place for it at each of the loop exits. */
  1095. if (FENCE_FOLLOWING_MOVNT != NULL_TREE)
  1096. {
  1097. vec<edge> exits = get_loop_exit_edges (loop);
  1098. unsigned i;
  1099. edge exit;
  1100. FOR_EACH_VEC_ELT (exits, i, exit)
  1101. if ((exit->flags & EDGE_ABNORMAL)
  1102. && exit->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
  1103. ret = false;
  1104. exits.release ();
  1105. }
  1106. return ret;
  1107. }
  1108. /* Marks nontemporal stores in LOOP. GROUPS contains the description of memory
  1109. references in the loop. */
  1110. static void
  1111. mark_nontemporal_stores (struct loop *loop, struct mem_ref_group *groups)
  1112. {
  1113. struct mem_ref *ref;
  1114. bool any = false;
  1115. if (!may_use_storent_in_loop_p (loop))
  1116. return;
  1117. for (; groups; groups = groups->next)
  1118. for (ref = groups->refs; ref; ref = ref->next)
  1119. any |= mark_nontemporal_store (ref);
  1120. if (any && FENCE_FOLLOWING_MOVNT != NULL_TREE)
  1121. emit_mfence_after_loop (loop);
  1122. }
  1123. /* Determines whether we can profitably unroll LOOP FACTOR times, and if
  1124. this is the case, fill in DESC by the description of number of
  1125. iterations. */
  1126. static bool
  1127. should_unroll_loop_p (struct loop *loop, struct tree_niter_desc *desc,
  1128. unsigned factor)
  1129. {
  1130. if (!can_unroll_loop_p (loop, factor, desc))
  1131. return false;
  1132. /* We only consider loops without control flow for unrolling. This is not
  1133. a hard restriction -- tree_unroll_loop works with arbitrary loops
  1134. as well; but the unrolling/prefetching is usually more profitable for
  1135. loops consisting of a single basic block, and we want to limit the
  1136. code growth. */
  1137. if (loop->num_nodes > 2)
  1138. return false;
  1139. return true;
  1140. }
  1141. /* Determine the coefficient by that unroll LOOP, from the information
  1142. contained in the list of memory references REFS. Description of
  1143. umber of iterations of LOOP is stored to DESC. NINSNS is the number of
  1144. insns of the LOOP. EST_NITER is the estimated number of iterations of
  1145. the loop, or -1 if no estimate is available. */
  1146. static unsigned
  1147. determine_unroll_factor (struct loop *loop, struct mem_ref_group *refs,
  1148. unsigned ninsns, struct tree_niter_desc *desc,
  1149. HOST_WIDE_INT est_niter)
  1150. {
  1151. unsigned upper_bound;
  1152. unsigned nfactor, factor, mod_constraint;
  1153. struct mem_ref_group *agp;
  1154. struct mem_ref *ref;
  1155. /* First check whether the loop is not too large to unroll. We ignore
  1156. PARAM_MAX_UNROLL_TIMES, because for small loops, it prevented us
  1157. from unrolling them enough to make exactly one cache line covered by each
  1158. iteration. Also, the goal of PARAM_MAX_UNROLL_TIMES is to prevent
  1159. us from unrolling the loops too many times in cases where we only expect
  1160. gains from better scheduling and decreasing loop overhead, which is not
  1161. the case here. */
  1162. upper_bound = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / ninsns;
  1163. /* If we unrolled the loop more times than it iterates, the unrolled version
  1164. of the loop would be never entered. */
  1165. if (est_niter >= 0 && est_niter < (HOST_WIDE_INT) upper_bound)
  1166. upper_bound = est_niter;
  1167. if (upper_bound <= 1)
  1168. return 1;
  1169. /* Choose the factor so that we may prefetch each cache just once,
  1170. but bound the unrolling by UPPER_BOUND. */
  1171. factor = 1;
  1172. for (agp = refs; agp; agp = agp->next)
  1173. for (ref = agp->refs; ref; ref = ref->next)
  1174. if (should_issue_prefetch_p (ref))
  1175. {
  1176. mod_constraint = ref->prefetch_mod;
  1177. nfactor = least_common_multiple (mod_constraint, factor);
  1178. if (nfactor <= upper_bound)
  1179. factor = nfactor;
  1180. }
  1181. if (!should_unroll_loop_p (loop, desc, factor))
  1182. return 1;
  1183. return factor;
  1184. }
  1185. /* Returns the total volume of the memory references REFS, taking into account
  1186. reuses in the innermost loop and cache line size. TODO -- we should also
  1187. take into account reuses across the iterations of the loops in the loop
  1188. nest. */
  1189. static unsigned
  1190. volume_of_references (struct mem_ref_group *refs)
  1191. {
  1192. unsigned volume = 0;
  1193. struct mem_ref_group *gr;
  1194. struct mem_ref *ref;
  1195. for (gr = refs; gr; gr = gr->next)
  1196. for (ref = gr->refs; ref; ref = ref->next)
  1197. {
  1198. /* Almost always reuses another value? */
  1199. if (ref->prefetch_before != PREFETCH_ALL)
  1200. continue;
  1201. /* If several iterations access the same cache line, use the size of
  1202. the line divided by this number. Otherwise, a cache line is
  1203. accessed in each iteration. TODO -- in the latter case, we should
  1204. take the size of the reference into account, rounding it up on cache
  1205. line size multiple. */
  1206. volume += L1_CACHE_LINE_SIZE / ref->prefetch_mod;
  1207. }
  1208. return volume;
  1209. }
  1210. /* Returns the volume of memory references accessed across VEC iterations of
  1211. loops, whose sizes are described in the LOOP_SIZES array. N is the number
  1212. of the loops in the nest (length of VEC and LOOP_SIZES vectors). */
  1213. static unsigned
  1214. volume_of_dist_vector (lambda_vector vec, unsigned *loop_sizes, unsigned n)
  1215. {
  1216. unsigned i;
  1217. for (i = 0; i < n; i++)
  1218. if (vec[i] != 0)
  1219. break;
  1220. if (i == n)
  1221. return 0;
  1222. gcc_assert (vec[i] > 0);
  1223. /* We ignore the parts of the distance vector in subloops, since usually
  1224. the numbers of iterations are much smaller. */
  1225. return loop_sizes[i] * vec[i];
  1226. }
  1227. /* Add the steps of ACCESS_FN multiplied by STRIDE to the array STRIDE
  1228. at the position corresponding to the loop of the step. N is the depth
  1229. of the considered loop nest, and, LOOP is its innermost loop. */
  1230. static void
  1231. add_subscript_strides (tree access_fn, unsigned stride,
  1232. HOST_WIDE_INT *strides, unsigned n, struct loop *loop)
  1233. {
  1234. struct loop *aloop;
  1235. tree step;
  1236. HOST_WIDE_INT astep;
  1237. unsigned min_depth = loop_depth (loop) - n;
  1238. while (TREE_CODE (access_fn) == POLYNOMIAL_CHREC)
  1239. {
  1240. aloop = get_chrec_loop (access_fn);
  1241. step = CHREC_RIGHT (access_fn);
  1242. access_fn = CHREC_LEFT (access_fn);
  1243. if ((unsigned) loop_depth (aloop) <= min_depth)
  1244. continue;
  1245. if (tree_fits_shwi_p (step))
  1246. astep = tree_to_shwi (step);
  1247. else
  1248. astep = L1_CACHE_LINE_SIZE;
  1249. strides[n - 1 - loop_depth (loop) + loop_depth (aloop)] += astep * stride;
  1250. }
  1251. }
  1252. /* Returns the volume of memory references accessed between two consecutive
  1253. self-reuses of the reference DR. We consider the subscripts of DR in N
  1254. loops, and LOOP_SIZES contains the volumes of accesses in each of the
  1255. loops. LOOP is the innermost loop of the current loop nest. */
  1256. static unsigned
  1257. self_reuse_distance (data_reference_p dr, unsigned *loop_sizes, unsigned n,
  1258. struct loop *loop)
  1259. {
  1260. tree stride, access_fn;
  1261. HOST_WIDE_INT *strides, astride;
  1262. vec<tree> access_fns;
  1263. tree ref = DR_REF (dr);
  1264. unsigned i, ret = ~0u;
  1265. /* In the following example:
  1266. for (i = 0; i < N; i++)
  1267. for (j = 0; j < N; j++)
  1268. use (a[j][i]);
  1269. the same cache line is accessed each N steps (except if the change from
  1270. i to i + 1 crosses the boundary of the cache line). Thus, for self-reuse,
  1271. we cannot rely purely on the results of the data dependence analysis.
  1272. Instead, we compute the stride of the reference in each loop, and consider
  1273. the innermost loop in that the stride is less than cache size. */
  1274. strides = XCNEWVEC (HOST_WIDE_INT, n);
  1275. access_fns = DR_ACCESS_FNS (dr);
  1276. FOR_EACH_VEC_ELT (access_fns, i, access_fn)
  1277. {
  1278. /* Keep track of the reference corresponding to the subscript, so that we
  1279. know its stride. */
  1280. while (handled_component_p (ref) && TREE_CODE (ref) != ARRAY_REF)
  1281. ref = TREE_OPERAND (ref, 0);
  1282. if (TREE_CODE (ref) == ARRAY_REF)
  1283. {
  1284. stride = TYPE_SIZE_UNIT (TREE_TYPE (ref));
  1285. if (tree_fits_uhwi_p (stride))
  1286. astride = tree_to_uhwi (stride);
  1287. else
  1288. astride = L1_CACHE_LINE_SIZE;
  1289. ref = TREE_OPERAND (ref, 0);
  1290. }
  1291. else
  1292. astride = 1;
  1293. add_subscript_strides (access_fn, astride, strides, n, loop);
  1294. }
  1295. for (i = n; i-- > 0; )
  1296. {
  1297. unsigned HOST_WIDE_INT s;
  1298. s = strides[i] < 0 ? -strides[i] : strides[i];
  1299. if (s < (unsigned) L1_CACHE_LINE_SIZE
  1300. && (loop_sizes[i]
  1301. > (unsigned) (L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION)))
  1302. {
  1303. ret = loop_sizes[i];
  1304. break;
  1305. }
  1306. }
  1307. free (strides);
  1308. return ret;
  1309. }
  1310. /* Determines the distance till the first reuse of each reference in REFS
  1311. in the loop nest of LOOP. NO_OTHER_REFS is true if there are no other
  1312. memory references in the loop. Return false if the analysis fails. */
  1313. static bool
  1314. determine_loop_nest_reuse (struct loop *loop, struct mem_ref_group *refs,
  1315. bool no_other_refs)
  1316. {
  1317. struct loop *nest, *aloop;
  1318. vec<data_reference_p> datarefs = vNULL;
  1319. vec<ddr_p> dependences = vNULL;
  1320. struct mem_ref_group *gr;
  1321. struct mem_ref *ref, *refb;
  1322. vec<loop_p> vloops = vNULL;
  1323. unsigned *loop_data_size;
  1324. unsigned i, j, n;
  1325. unsigned volume, dist, adist;
  1326. HOST_WIDE_INT vol;
  1327. data_reference_p dr;
  1328. ddr_p dep;
  1329. if (loop->inner)
  1330. return true;
  1331. /* Find the outermost loop of the loop nest of loop (we require that
  1332. there are no sibling loops inside the nest). */
  1333. nest = loop;
  1334. while (1)
  1335. {
  1336. aloop = loop_outer (nest);
  1337. if (aloop == current_loops->tree_root
  1338. || aloop->inner->next)
  1339. break;
  1340. nest = aloop;
  1341. }
  1342. /* For each loop, determine the amount of data accessed in each iteration.
  1343. We use this to estimate whether the reference is evicted from the
  1344. cache before its reuse. */
  1345. find_loop_nest (nest, &vloops);
  1346. n = vloops.length ();
  1347. loop_data_size = XNEWVEC (unsigned, n);
  1348. volume = volume_of_references (refs);
  1349. i = n;
  1350. while (i-- != 0)
  1351. {
  1352. loop_data_size[i] = volume;
  1353. /* Bound the volume by the L2 cache size, since above this bound,
  1354. all dependence distances are equivalent. */
  1355. if (volume > L2_CACHE_SIZE_BYTES)
  1356. continue;
  1357. aloop = vloops[i];
  1358. vol = estimated_stmt_executions_int (aloop);
  1359. if (vol == -1)
  1360. vol = expected_loop_iterations (aloop);
  1361. volume *= vol;
  1362. }
  1363. /* Prepare the references in the form suitable for data dependence
  1364. analysis. We ignore unanalyzable data references (the results
  1365. are used just as a heuristics to estimate temporality of the
  1366. references, hence we do not need to worry about correctness). */
  1367. for (gr = refs; gr; gr = gr->next)
  1368. for (ref = gr->refs; ref; ref = ref->next)
  1369. {
  1370. dr = create_data_ref (nest, loop_containing_stmt (ref->stmt),
  1371. ref->mem, ref->stmt, !ref->write_p);
  1372. if (dr)
  1373. {
  1374. ref->reuse_distance = volume;
  1375. dr->aux = ref;
  1376. datarefs.safe_push (dr);
  1377. }
  1378. else
  1379. no_other_refs = false;
  1380. }
  1381. FOR_EACH_VEC_ELT (datarefs, i, dr)
  1382. {
  1383. dist = self_reuse_distance (dr, loop_data_size, n, loop);
  1384. ref = (struct mem_ref *) dr->aux;
  1385. if (ref->reuse_distance > dist)
  1386. ref->reuse_distance = dist;
  1387. if (no_other_refs)
  1388. ref->independent_p = true;
  1389. }
  1390. if (!compute_all_dependences (datarefs, &dependences, vloops, true))
  1391. return false;
  1392. FOR_EACH_VEC_ELT (dependences, i, dep)
  1393. {
  1394. if (DDR_ARE_DEPENDENT (dep) == chrec_known)
  1395. continue;
  1396. ref = (struct mem_ref *) DDR_A (dep)->aux;
  1397. refb = (struct mem_ref *) DDR_B (dep)->aux;
  1398. if (DDR_ARE_DEPENDENT (dep) == chrec_dont_know
  1399. || DDR_NUM_DIST_VECTS (dep) == 0)
  1400. {
  1401. /* If the dependence cannot be analyzed, assume that there might be
  1402. a reuse. */
  1403. dist = 0;
  1404. ref->independent_p = false;
  1405. refb->independent_p = false;
  1406. }
  1407. else
  1408. {
  1409. /* The distance vectors are normalized to be always lexicographically
  1410. positive, hence we cannot tell just from them whether DDR_A comes
  1411. before DDR_B or vice versa. However, it is not important,
  1412. anyway -- if DDR_A is close to DDR_B, then it is either reused in
  1413. DDR_B (and it is not nontemporal), or it reuses the value of DDR_B
  1414. in cache (and marking it as nontemporal would not affect
  1415. anything). */
  1416. dist = volume;
  1417. for (j = 0; j < DDR_NUM_DIST_VECTS (dep); j++)
  1418. {
  1419. adist = volume_of_dist_vector (DDR_DIST_VECT (dep, j),
  1420. loop_data_size, n);
  1421. /* If this is a dependence in the innermost loop (i.e., the
  1422. distances in all superloops are zero) and it is not
  1423. the trivial self-dependence with distance zero, record that
  1424. the references are not completely independent. */
  1425. if (lambda_vector_zerop (DDR_DIST_VECT (dep, j), n - 1)
  1426. && (ref != refb
  1427. || DDR_DIST_VECT (dep, j)[n-1] != 0))
  1428. {
  1429. ref->independent_p = false;
  1430. refb->independent_p = false;
  1431. }
  1432. /* Ignore accesses closer than
  1433. L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION,
  1434. so that we use nontemporal prefetches e.g. if single memory
  1435. location is accessed several times in a single iteration of
  1436. the loop. */
  1437. if (adist < L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION)
  1438. continue;
  1439. if (adist < dist)
  1440. dist = adist;
  1441. }
  1442. }
  1443. if (ref->reuse_distance > dist)
  1444. ref->reuse_distance = dist;
  1445. if (refb->reuse_distance > dist)
  1446. refb->reuse_distance = dist;
  1447. }
  1448. free_dependence_relations (dependences);
  1449. free_data_refs (datarefs);
  1450. free (loop_data_size);
  1451. if (dump_file && (dump_flags & TDF_DETAILS))
  1452. {
  1453. fprintf (dump_file, "Reuse distances:\n");
  1454. for (gr = refs; gr; gr = gr->next)
  1455. for (ref = gr->refs; ref; ref = ref->next)
  1456. fprintf (dump_file, " ref %p distance %u\n",
  1457. (void *) ref, ref->reuse_distance);
  1458. }
  1459. return true;
  1460. }
  1461. /* Determine whether or not the trip count to ahead ratio is too small based
  1462. on prefitablility consideration.
  1463. AHEAD: the iteration ahead distance,
  1464. EST_NITER: the estimated trip count. */
  1465. static bool
  1466. trip_count_to_ahead_ratio_too_small_p (unsigned ahead, HOST_WIDE_INT est_niter)
  1467. {
  1468. /* Assume trip count to ahead ratio is big enough if the trip count could not
  1469. be estimated at compile time. */
  1470. if (est_niter < 0)
  1471. return false;
  1472. if (est_niter < (HOST_WIDE_INT) (TRIP_COUNT_TO_AHEAD_RATIO * ahead))
  1473. {
  1474. if (dump_file && (dump_flags & TDF_DETAILS))
  1475. fprintf (dump_file,
  1476. "Not prefetching -- loop estimated to roll only %d times\n",
  1477. (int) est_niter);
  1478. return true;
  1479. }
  1480. return false;
  1481. }
  1482. /* Determine whether or not the number of memory references in the loop is
  1483. reasonable based on the profitablity and compilation time considerations.
  1484. NINSNS: estimated number of instructions in the loop,
  1485. MEM_REF_COUNT: total number of memory references in the loop. */
  1486. static bool
  1487. mem_ref_count_reasonable_p (unsigned ninsns, unsigned mem_ref_count)
  1488. {
  1489. int insn_to_mem_ratio;
  1490. if (mem_ref_count == 0)
  1491. return false;
  1492. /* Miss rate computation (is_miss_rate_acceptable) and dependence analysis
  1493. (compute_all_dependences) have high costs based on quadratic complexity.
  1494. To avoid huge compilation time, we give up prefetching if mem_ref_count
  1495. is too large. */
  1496. if (mem_ref_count > PREFETCH_MAX_MEM_REFS_PER_LOOP)
  1497. return false;
  1498. /* Prefetching improves performance by overlapping cache missing
  1499. memory accesses with CPU operations. If the loop does not have
  1500. enough CPU operations to overlap with memory operations, prefetching
  1501. won't give a significant benefit. One approximate way of checking
  1502. this is to require the ratio of instructions to memory references to
  1503. be above a certain limit. This approximation works well in practice.
  1504. TODO: Implement a more precise computation by estimating the time
  1505. for each CPU or memory op in the loop. Time estimates for memory ops
  1506. should account for cache misses. */
  1507. insn_to_mem_ratio = ninsns / mem_ref_count;
  1508. if (insn_to_mem_ratio < PREFETCH_MIN_INSN_TO_MEM_RATIO)
  1509. {
  1510. if (dump_file && (dump_flags & TDF_DETAILS))
  1511. fprintf (dump_file,
  1512. "Not prefetching -- instruction to memory reference ratio (%d) too small\n",
  1513. insn_to_mem_ratio);
  1514. return false;
  1515. }
  1516. return true;
  1517. }
  1518. /* Determine whether or not the instruction to prefetch ratio in the loop is
  1519. too small based on the profitablity consideration.
  1520. NINSNS: estimated number of instructions in the loop,
  1521. PREFETCH_COUNT: an estimate of the number of prefetches,
  1522. UNROLL_FACTOR: the factor to unroll the loop if prefetching. */
  1523. static bool
  1524. insn_to_prefetch_ratio_too_small_p (unsigned ninsns, unsigned prefetch_count,
  1525. unsigned unroll_factor)
  1526. {
  1527. int insn_to_prefetch_ratio;
  1528. /* Prefetching most likely causes performance degradation when the instruction
  1529. to prefetch ratio is too small. Too many prefetch instructions in a loop
  1530. may reduce the I-cache performance.
  1531. (unroll_factor * ninsns) is used to estimate the number of instructions in
  1532. the unrolled loop. This implementation is a bit simplistic -- the number
  1533. of issued prefetch instructions is also affected by unrolling. So,
  1534. prefetch_mod and the unroll factor should be taken into account when
  1535. determining prefetch_count. Also, the number of insns of the unrolled
  1536. loop will usually be significantly smaller than the number of insns of the
  1537. original loop * unroll_factor (at least the induction variable increases
  1538. and the exit branches will get eliminated), so it might be better to use
  1539. tree_estimate_loop_size + estimated_unrolled_size. */
  1540. insn_to_prefetch_ratio = (unroll_factor * ninsns) / prefetch_count;
  1541. if (insn_to_prefetch_ratio < MIN_INSN_TO_PREFETCH_RATIO)
  1542. {
  1543. if (dump_file && (dump_flags & TDF_DETAILS))
  1544. fprintf (dump_file,
  1545. "Not prefetching -- instruction to prefetch ratio (%d) too small\n",
  1546. insn_to_prefetch_ratio);
  1547. return true;
  1548. }
  1549. return false;
  1550. }
  1551. /* Issue prefetch instructions for array references in LOOP. Returns
  1552. true if the LOOP was unrolled. */
  1553. static bool
  1554. loop_prefetch_arrays (struct loop *loop)
  1555. {
  1556. struct mem_ref_group *refs;
  1557. unsigned ahead, ninsns, time, unroll_factor;
  1558. HOST_WIDE_INT est_niter;
  1559. struct tree_niter_desc desc;
  1560. bool unrolled = false, no_other_refs;
  1561. unsigned prefetch_count;
  1562. unsigned mem_ref_count;
  1563. if (optimize_loop_nest_for_size_p (loop))
  1564. {
  1565. if (dump_file && (dump_flags & TDF_DETAILS))
  1566. fprintf (dump_file, " ignored (cold area)\n");
  1567. return false;
  1568. }
  1569. /* FIXME: the time should be weighted by the probabilities of the blocks in
  1570. the loop body. */
  1571. time = tree_num_loop_insns (loop, &eni_time_weights);
  1572. if (time == 0)
  1573. return false;
  1574. ahead = (PREFETCH_LATENCY + time - 1) / time;
  1575. est_niter = estimated_stmt_executions_int (loop);
  1576. if (est_niter == -1)
  1577. est_niter = max_stmt_executions_int (loop);
  1578. /* Prefetching is not likely to be profitable if the trip count to ahead
  1579. ratio is too small. */
  1580. if (trip_count_to_ahead_ratio_too_small_p (ahead, est_niter))
  1581. return false;
  1582. ninsns = tree_num_loop_insns (loop, &eni_size_weights);
  1583. /* Step 1: gather the memory references. */
  1584. refs = gather_memory_references (loop, &no_other_refs, &mem_ref_count);
  1585. /* Give up prefetching if the number of memory references in the
  1586. loop is not reasonable based on profitablity and compilation time
  1587. considerations. */
  1588. if (!mem_ref_count_reasonable_p (ninsns, mem_ref_count))
  1589. goto fail;
  1590. /* Step 2: estimate the reuse effects. */
  1591. prune_by_reuse (refs);
  1592. if (nothing_to_prefetch_p (refs))
  1593. goto fail;
  1594. if (!determine_loop_nest_reuse (loop, refs, no_other_refs))
  1595. goto fail;
  1596. /* Step 3: determine unroll factor. */
  1597. unroll_factor = determine_unroll_factor (loop, refs, ninsns, &desc,
  1598. est_niter);
  1599. /* Estimate prefetch count for the unrolled loop. */
  1600. prefetch_count = estimate_prefetch_count (refs, unroll_factor);
  1601. if (prefetch_count == 0)
  1602. goto fail;
  1603. if (dump_file && (dump_flags & TDF_DETAILS))
  1604. fprintf (dump_file, "Ahead %d, unroll factor %d, trip count "
  1605. HOST_WIDE_INT_PRINT_DEC "\n"
  1606. "insn count %d, mem ref count %d, prefetch count %d\n",
  1607. ahead, unroll_factor, est_niter,
  1608. ninsns, mem_ref_count, prefetch_count);
  1609. /* Prefetching is not likely to be profitable if the instruction to prefetch
  1610. ratio is too small. */
  1611. if (insn_to_prefetch_ratio_too_small_p (ninsns, prefetch_count,
  1612. unroll_factor))
  1613. goto fail;
  1614. mark_nontemporal_stores (loop, refs);
  1615. /* Step 4: what to prefetch? */
  1616. if (!schedule_prefetches (refs, unroll_factor, ahead))
  1617. goto fail;
  1618. /* Step 5: unroll the loop. TODO -- peeling of first and last few
  1619. iterations so that we do not issue superfluous prefetches. */
  1620. if (unroll_factor != 1)
  1621. {
  1622. tree_unroll_loop (loop, unroll_factor,
  1623. single_dom_exit (loop), &desc);
  1624. unrolled = true;
  1625. }
  1626. /* Step 6: issue the prefetches. */
  1627. issue_prefetches (refs, unroll_factor, ahead);
  1628. fail:
  1629. release_mem_refs (refs);
  1630. return unrolled;
  1631. }
  1632. /* Issue prefetch instructions for array references in loops. */
  1633. unsigned int
  1634. tree_ssa_prefetch_arrays (void)
  1635. {
  1636. struct loop *loop;
  1637. bool unrolled = false;
  1638. int todo_flags = 0;
  1639. if (!HAVE_prefetch
  1640. /* It is possible to ask compiler for say -mtune=i486 -march=pentium4.
  1641. -mtune=i486 causes us having PREFETCH_BLOCK 0, since this is part
  1642. of processor costs and i486 does not have prefetch, but
  1643. -march=pentium4 causes HAVE_prefetch to be true. Ugh. */
  1644. || PREFETCH_BLOCK == 0)
  1645. return 0;
  1646. if (dump_file && (dump_flags & TDF_DETAILS))
  1647. {
  1648. fprintf (dump_file, "Prefetching parameters:\n");
  1649. fprintf (dump_file, " simultaneous prefetches: %d\n",
  1650. SIMULTANEOUS_PREFETCHES);
  1651. fprintf (dump_file, " prefetch latency: %d\n", PREFETCH_LATENCY);
  1652. fprintf (dump_file, " prefetch block size: %d\n", PREFETCH_BLOCK);
  1653. fprintf (dump_file, " L1 cache size: %d lines, %d kB\n",
  1654. L1_CACHE_SIZE_BYTES / L1_CACHE_LINE_SIZE, L1_CACHE_SIZE);
  1655. fprintf (dump_file, " L1 cache line size: %d\n", L1_CACHE_LINE_SIZE);
  1656. fprintf (dump_file, " L2 cache size: %d kB\n", L2_CACHE_SIZE);
  1657. fprintf (dump_file, " min insn-to-prefetch ratio: %d \n",
  1658. MIN_INSN_TO_PREFETCH_RATIO);
  1659. fprintf (dump_file, " min insn-to-mem ratio: %d \n",
  1660. PREFETCH_MIN_INSN_TO_MEM_RATIO);
  1661. fprintf (dump_file, "\n");
  1662. }
  1663. initialize_original_copy_tables ();
  1664. if (!builtin_decl_explicit_p (BUILT_IN_PREFETCH))
  1665. {
  1666. tree type = build_function_type_list (void_type_node,
  1667. const_ptr_type_node, NULL_TREE);
  1668. tree decl = add_builtin_function ("__builtin_prefetch", type,
  1669. BUILT_IN_PREFETCH, BUILT_IN_NORMAL,
  1670. NULL, NULL_TREE);
  1671. DECL_IS_NOVOPS (decl) = true;
  1672. set_builtin_decl (BUILT_IN_PREFETCH, decl, false);
  1673. }
  1674. /* We assume that size of cache line is a power of two, so verify this
  1675. here. */
  1676. gcc_assert ((PREFETCH_BLOCK & (PREFETCH_BLOCK - 1)) == 0);
  1677. FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
  1678. {
  1679. if (dump_file && (dump_flags & TDF_DETAILS))
  1680. fprintf (dump_file, "Processing loop %d:\n", loop->num);
  1681. unrolled |= loop_prefetch_arrays (loop);
  1682. if (dump_file && (dump_flags & TDF_DETAILS))
  1683. fprintf (dump_file, "\n\n");
  1684. }
  1685. if (unrolled)
  1686. {
  1687. scev_reset ();
  1688. todo_flags |= TODO_cleanup_cfg;
  1689. }
  1690. free_original_copy_tables ();
  1691. return todo_flags;
  1692. }
  1693. /* Prefetching. */
  1694. namespace {
  1695. const pass_data pass_data_loop_prefetch =
  1696. {
  1697. GIMPLE_PASS, /* type */
  1698. "aprefetch", /* name */
  1699. OPTGROUP_LOOP, /* optinfo_flags */
  1700. TV_TREE_PREFETCH, /* tv_id */
  1701. ( PROP_cfg | PROP_ssa ), /* properties_required */
  1702. 0, /* properties_provided */
  1703. 0, /* properties_destroyed */
  1704. 0, /* todo_flags_start */
  1705. 0, /* todo_flags_finish */
  1706. };
  1707. class pass_loop_prefetch : public gimple_opt_pass
  1708. {
  1709. public:
  1710. pass_loop_prefetch (gcc::context *ctxt)
  1711. : gimple_opt_pass (pass_data_loop_prefetch, ctxt)
  1712. {}
  1713. /* opt_pass methods: */
  1714. virtual bool gate (function *) { return flag_prefetch_loop_arrays > 0; }
  1715. virtual unsigned int execute (function *);
  1716. }; // class pass_loop_prefetch
  1717. unsigned int
  1718. pass_loop_prefetch::execute (function *fun)
  1719. {
  1720. if (number_of_loops (fun) <= 1)
  1721. return 0;
  1722. return tree_ssa_prefetch_arrays ();
  1723. }
  1724. } // anon namespace
  1725. gimple_opt_pass *
  1726. make_pass_loop_prefetch (gcc::context *ctxt)
  1727. {
  1728. return new pass_loop_prefetch (ctxt);
  1729. }