ProgrammersManual.html 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  2. "http://www.w3.org/TR/html4/strict.dtd">
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
  6. <title>LLVM Programmer's Manual</title>
  7. <link rel="stylesheet" href="llvm.css" type="text/css">
  8. </head>
  9. <body>
  10. <div class="doc_title">
  11. LLVM Programmer's Manual
  12. </div>
  13. <ol>
  14. <li><a href="#introduction">Introduction</a></li>
  15. <li><a href="#general">General Information</a>
  16. <ul>
  17. <li><a href="#stl">The C++ Standard Template Library</a></li>
  18. <!--
  19. <li>The <tt>-time-passes</tt> option</li>
  20. <li>How to use the LLVM Makefile system</li>
  21. <li>How to write a regression test</li>
  22. -->
  23. </ul>
  24. </li>
  25. <li><a href="#apis">Important and useful LLVM APIs</a>
  26. <ul>
  27. <li><a href="#isa">The <tt>isa&lt;&gt;</tt>, <tt>cast&lt;&gt;</tt>
  28. and <tt>dyn_cast&lt;&gt;</tt> templates</a> </li>
  29. <li><a href="#string_apis">Passing strings (the <tt>StringRef</tt>
  30. and <tt>Twine</tt> classes)</a>
  31. <ul>
  32. <li><a href="#StringRef">The <tt>StringRef</tt> class</a> </li>
  33. <li><a href="#Twine">The <tt>Twine</tt> class</a> </li>
  34. </ul>
  35. </li>
  36. <li><a href="#DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt>
  37. option</a>
  38. <ul>
  39. <li><a href="#DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt>
  40. and the <tt>-debug-only</tt> option</a> </li>
  41. </ul>
  42. </li>
  43. <li><a href="#Statistic">The <tt>Statistic</tt> class &amp; <tt>-stats</tt>
  44. option</a></li>
  45. <!--
  46. <li>The <tt>InstVisitor</tt> template
  47. <li>The general graph API
  48. -->
  49. <li><a href="#ViewGraph">Viewing graphs while debugging code</a></li>
  50. </ul>
  51. </li>
  52. <li><a href="#datastructure">Picking the Right Data Structure for a Task</a>
  53. <ul>
  54. <li><a href="#ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
  55. <ul>
  56. <li><a href="#dss_fixedarrays">Fixed Size Arrays</a></li>
  57. <li><a href="#dss_heaparrays">Heap Allocated Arrays</a></li>
  58. <li><a href="#dss_smallvector">"llvm/ADT/SmallVector.h"</a></li>
  59. <li><a href="#dss_vector">&lt;vector&gt;</a></li>
  60. <li><a href="#dss_deque">&lt;deque&gt;</a></li>
  61. <li><a href="#dss_list">&lt;list&gt;</a></li>
  62. <li><a href="#dss_ilist">llvm/ADT/ilist.h</a></li>
  63. <li><a href="#dss_other">Other Sequential Container Options</a></li>
  64. </ul></li>
  65. <li><a href="#ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
  66. <ul>
  67. <li><a href="#dss_sortedvectorset">A sorted 'vector'</a></li>
  68. <li><a href="#dss_smallset">"llvm/ADT/SmallSet.h"</a></li>
  69. <li><a href="#dss_smallptrset">"llvm/ADT/SmallPtrSet.h"</a></li>
  70. <li><a href="#dss_denseset">"llvm/ADT/DenseSet.h"</a></li>
  71. <li><a href="#dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a></li>
  72. <li><a href="#dss_set">&lt;set&gt;</a></li>
  73. <li><a href="#dss_setvector">"llvm/ADT/SetVector.h"</a></li>
  74. <li><a href="#dss_uniquevector">"llvm/ADT/UniqueVector.h"</a></li>
  75. <li><a href="#dss_otherset">Other Set-Like ContainerOptions</a></li>
  76. </ul></li>
  77. <li><a href="#ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
  78. <ul>
  79. <li><a href="#dss_sortedvectormap">A sorted 'vector'</a></li>
  80. <li><a href="#dss_stringmap">"llvm/ADT/StringMap.h"</a></li>
  81. <li><a href="#dss_indexedmap">"llvm/ADT/IndexedMap.h"</a></li>
  82. <li><a href="#dss_densemap">"llvm/ADT/DenseMap.h"</a></li>
  83. <li><a href="#dss_valuemap">"llvm/ADT/ValueMap.h"</a></li>
  84. <li><a href="#dss_map">&lt;map&gt;</a></li>
  85. <li><a href="#dss_othermap">Other Map-Like Container Options</a></li>
  86. </ul></li>
  87. <li><a href="#ds_string">String-like containers</a>
  88. <!--<ul>
  89. todo
  90. </ul>--></li>
  91. <li><a href="#ds_bit">BitVector-like containers</a>
  92. <ul>
  93. <li><a href="#dss_bitvector">A dense bitvector</a></li>
  94. <li><a href="#dss_smallbitvector">A "small" dense bitvector</a></li>
  95. <li><a href="#dss_sparsebitvector">A sparse bitvector</a></li>
  96. </ul></li>
  97. </ul>
  98. </li>
  99. <li><a href="#common">Helpful Hints for Common Operations</a>
  100. <ul>
  101. <li><a href="#inspection">Basic Inspection and Traversal Routines</a>
  102. <ul>
  103. <li><a href="#iterate_function">Iterating over the <tt>BasicBlock</tt>s
  104. in a <tt>Function</tt></a> </li>
  105. <li><a href="#iterate_basicblock">Iterating over the <tt>Instruction</tt>s
  106. in a <tt>BasicBlock</tt></a> </li>
  107. <li><a href="#iterate_institer">Iterating over the <tt>Instruction</tt>s
  108. in a <tt>Function</tt></a> </li>
  109. <li><a href="#iterate_convert">Turning an iterator into a
  110. class pointer</a> </li>
  111. <li><a href="#iterate_complex">Finding call sites: a more
  112. complex example</a> </li>
  113. <li><a href="#calls_and_invokes">Treating calls and invokes
  114. the same way</a> </li>
  115. <li><a href="#iterate_chains">Iterating over def-use &amp;
  116. use-def chains</a> </li>
  117. <li><a href="#iterate_preds">Iterating over predecessors &amp;
  118. successors of blocks</a></li>
  119. </ul>
  120. </li>
  121. <li><a href="#simplechanges">Making simple changes</a>
  122. <ul>
  123. <li><a href="#schanges_creating">Creating and inserting new
  124. <tt>Instruction</tt>s</a> </li>
  125. <li><a href="#schanges_deleting">Deleting <tt>Instruction</tt>s</a> </li>
  126. <li><a href="#schanges_replacing">Replacing an <tt>Instruction</tt>
  127. with another <tt>Value</tt></a> </li>
  128. <li><a href="#schanges_deletingGV">Deleting <tt>GlobalVariable</tt>s</a> </li>
  129. </ul>
  130. </li>
  131. <li><a href="#create_types">How to Create Types</a></li>
  132. <!--
  133. <li>Working with the Control Flow Graph
  134. <ul>
  135. <li>Accessing predecessors and successors of a <tt>BasicBlock</tt>
  136. <li>
  137. <li>
  138. </ul>
  139. -->
  140. </ul>
  141. </li>
  142. <li><a href="#threading">Threads and LLVM</a>
  143. <ul>
  144. <li><a href="#startmultithreaded">Entering and Exiting Multithreaded Mode
  145. </a></li>
  146. <li><a href="#shutdown">Ending execution with <tt>llvm_shutdown()</tt></a></li>
  147. <li><a href="#managedstatic">Lazy initialization with <tt>ManagedStatic</tt></a></li>
  148. <li><a href="#llvmcontext">Achieving Isolation with <tt>LLVMContext</tt></a></li>
  149. <li><a href="#jitthreading">Threads and the JIT</a></li>
  150. </ul>
  151. </li>
  152. <li><a href="#advanced">Advanced Topics</a>
  153. <ul>
  154. <li><a href="#TypeResolve">LLVM Type Resolution</a>
  155. <ul>
  156. <li><a href="#BuildRecType">Basic Recursive Type Construction</a></li>
  157. <li><a href="#refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a></li>
  158. <li><a href="#PATypeHolder">The PATypeHolder Class</a></li>
  159. <li><a href="#AbstractTypeUser">The AbstractTypeUser Class</a></li>
  160. </ul></li>
  161. <li><a href="#SymbolTable">The <tt>ValueSymbolTable</tt> and <tt>TypeSymbolTable</tt> classes</a></li>
  162. <li><a href="#UserLayout">The <tt>User</tt> and owned <tt>Use</tt> classes' memory layout</a></li>
  163. </ul></li>
  164. <li><a href="#coreclasses">The Core LLVM Class Hierarchy Reference</a>
  165. <ul>
  166. <li><a href="#Type">The <tt>Type</tt> class</a> </li>
  167. <li><a href="#Module">The <tt>Module</tt> class</a></li>
  168. <li><a href="#Value">The <tt>Value</tt> class</a>
  169. <ul>
  170. <li><a href="#User">The <tt>User</tt> class</a>
  171. <ul>
  172. <li><a href="#Instruction">The <tt>Instruction</tt> class</a></li>
  173. <li><a href="#Constant">The <tt>Constant</tt> class</a>
  174. <ul>
  175. <li><a href="#GlobalValue">The <tt>GlobalValue</tt> class</a>
  176. <ul>
  177. <li><a href="#Function">The <tt>Function</tt> class</a></li>
  178. <li><a href="#GlobalVariable">The <tt>GlobalVariable</tt> class</a></li>
  179. </ul>
  180. </li>
  181. </ul>
  182. </li>
  183. </ul>
  184. </li>
  185. <li><a href="#BasicBlock">The <tt>BasicBlock</tt> class</a></li>
  186. <li><a href="#Argument">The <tt>Argument</tt> class</a></li>
  187. </ul>
  188. </li>
  189. </ul>
  190. </li>
  191. </ol>
  192. <div class="doc_author">
  193. <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>,
  194. <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a>,
  195. <a href="mailto:ggreif@gmail.com">Gabor Greif</a>,
  196. <a href="mailto:jstanley@cs.uiuc.edu">Joel Stanley</a>,
  197. <a href="mailto:rspencer@x10sys.com">Reid Spencer</a> and
  198. <a href="mailto:owen@apple.com">Owen Anderson</a></p>
  199. </div>
  200. <!-- *********************************************************************** -->
  201. <div class="doc_section">
  202. <a name="introduction">Introduction </a>
  203. </div>
  204. <!-- *********************************************************************** -->
  205. <div class="doc_text">
  206. <p>This document is meant to highlight some of the important classes and
  207. interfaces available in the LLVM source-base. This manual is not
  208. intended to explain what LLVM is, how it works, and what LLVM code looks
  209. like. It assumes that you know the basics of LLVM and are interested
  210. in writing transformations or otherwise analyzing or manipulating the
  211. code.</p>
  212. <p>This document should get you oriented so that you can find your
  213. way in the continuously growing source code that makes up the LLVM
  214. infrastructure. Note that this manual is not intended to serve as a
  215. replacement for reading the source code, so if you think there should be
  216. a method in one of these classes to do something, but it's not listed,
  217. check the source. Links to the <a href="/doxygen/">doxygen</a> sources
  218. are provided to make this as easy as possible.</p>
  219. <p>The first section of this document describes general information that is
  220. useful to know when working in the LLVM infrastructure, and the second describes
  221. the Core LLVM classes. In the future this manual will be extended with
  222. information describing how to use extension libraries, such as dominator
  223. information, CFG traversal routines, and useful utilities like the <tt><a
  224. href="/doxygen/InstVisitor_8h-source.html">InstVisitor</a></tt> template.</p>
  225. </div>
  226. <!-- *********************************************************************** -->
  227. <div class="doc_section">
  228. <a name="general">General Information</a>
  229. </div>
  230. <!-- *********************************************************************** -->
  231. <div class="doc_text">
  232. <p>This section contains general information that is useful if you are working
  233. in the LLVM source-base, but that isn't specific to any particular API.</p>
  234. </div>
  235. <!-- ======================================================================= -->
  236. <div class="doc_subsection">
  237. <a name="stl">The C++ Standard Template Library</a>
  238. </div>
  239. <div class="doc_text">
  240. <p>LLVM makes heavy use of the C++ Standard Template Library (STL),
  241. perhaps much more than you are used to, or have seen before. Because of
  242. this, you might want to do a little background reading in the
  243. techniques used and capabilities of the library. There are many good
  244. pages that discuss the STL, and several books on the subject that you
  245. can get, so it will not be discussed in this document.</p>
  246. <p>Here are some useful links:</p>
  247. <ol>
  248. <li><a href="http://www.dinkumware.com/refxcpp.html">Dinkumware C++ Library
  249. reference</a> - an excellent reference for the STL and other parts of the
  250. standard C++ library.</li>
  251. <li><a href="http://www.tempest-sw.com/cpp/">C++ In a Nutshell</a> - This is an
  252. O'Reilly book in the making. It has a decent Standard Library
  253. Reference that rivals Dinkumware's, and is unfortunately no longer free since the
  254. book has been published.</li>
  255. <li><a href="http://www.parashift.com/c++-faq-lite/">C++ Frequently Asked
  256. Questions</a></li>
  257. <li><a href="http://www.sgi.com/tech/stl/">SGI's STL Programmer's Guide</a> -
  258. Contains a useful <a
  259. href="http://www.sgi.com/tech/stl/stl_introduction.html">Introduction to the
  260. STL</a>.</li>
  261. <li><a href="http://www.research.att.com/%7Ebs/C++.html">Bjarne Stroustrup's C++
  262. Page</a></li>
  263. <li><a href="http://64.78.49.204/">
  264. Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0 (even better, get
  265. the book).</a></li>
  266. </ol>
  267. <p>You are also encouraged to take a look at the <a
  268. href="CodingStandards.html">LLVM Coding Standards</a> guide which focuses on how
  269. to write maintainable code more than where to put your curly braces.</p>
  270. </div>
  271. <!-- ======================================================================= -->
  272. <div class="doc_subsection">
  273. <a name="stl">Other useful references</a>
  274. </div>
  275. <div class="doc_text">
  276. <ol>
  277. <li><a href="http://www.psc.edu/%7Esemke/cvs_branches.html">CVS
  278. Branch and Tag Primer</a></li>
  279. <li><a href="http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html">Using
  280. static and shared libraries across platforms</a></li>
  281. </ol>
  282. </div>
  283. <!-- *********************************************************************** -->
  284. <div class="doc_section">
  285. <a name="apis">Important and useful LLVM APIs</a>
  286. </div>
  287. <!-- *********************************************************************** -->
  288. <div class="doc_text">
  289. <p>Here we highlight some LLVM APIs that are generally useful and good to
  290. know about when writing transformations.</p>
  291. </div>
  292. <!-- ======================================================================= -->
  293. <div class="doc_subsection">
  294. <a name="isa">The <tt>isa&lt;&gt;</tt>, <tt>cast&lt;&gt;</tt> and
  295. <tt>dyn_cast&lt;&gt;</tt> templates</a>
  296. </div>
  297. <div class="doc_text">
  298. <p>The LLVM source-base makes extensive use of a custom form of RTTI.
  299. These templates have many similarities to the C++ <tt>dynamic_cast&lt;&gt;</tt>
  300. operator, but they don't have some drawbacks (primarily stemming from
  301. the fact that <tt>dynamic_cast&lt;&gt;</tt> only works on classes that
  302. have a v-table). Because they are used so often, you must know what they
  303. do and how they work. All of these templates are defined in the <a
  304. href="/doxygen/Casting_8h-source.html"><tt>llvm/Support/Casting.h</tt></a>
  305. file (note that you very rarely have to include this file directly).</p>
  306. <dl>
  307. <dt><tt>isa&lt;&gt;</tt>: </dt>
  308. <dd><p>The <tt>isa&lt;&gt;</tt> operator works exactly like the Java
  309. "<tt>instanceof</tt>" operator. It returns true or false depending on whether
  310. a reference or pointer points to an instance of the specified class. This can
  311. be very useful for constraint checking of various sorts (example below).</p>
  312. </dd>
  313. <dt><tt>cast&lt;&gt;</tt>: </dt>
  314. <dd><p>The <tt>cast&lt;&gt;</tt> operator is a "checked cast" operation. It
  315. converts a pointer or reference from a base class to a derived class, causing
  316. an assertion failure if it is not really an instance of the right type. This
  317. should be used in cases where you have some information that makes you believe
  318. that something is of the right type. An example of the <tt>isa&lt;&gt;</tt>
  319. and <tt>cast&lt;&gt;</tt> template is:</p>
  320. <div class="doc_code">
  321. <pre>
  322. static bool isLoopInvariant(const <a href="#Value">Value</a> *V, const Loop *L) {
  323. if (isa&lt;<a href="#Constant">Constant</a>&gt;(V) || isa&lt;<a href="#Argument">Argument</a>&gt;(V) || isa&lt;<a href="#GlobalValue">GlobalValue</a>&gt;(V))
  324. return true;
  325. // <i>Otherwise, it must be an instruction...</i>
  326. return !L-&gt;contains(cast&lt;<a href="#Instruction">Instruction</a>&gt;(V)-&gt;getParent());
  327. }
  328. </pre>
  329. </div>
  330. <p>Note that you should <b>not</b> use an <tt>isa&lt;&gt;</tt> test followed
  331. by a <tt>cast&lt;&gt;</tt>, for that use the <tt>dyn_cast&lt;&gt;</tt>
  332. operator.</p>
  333. </dd>
  334. <dt><tt>dyn_cast&lt;&gt;</tt>:</dt>
  335. <dd><p>The <tt>dyn_cast&lt;&gt;</tt> operator is a "checking cast" operation.
  336. It checks to see if the operand is of the specified type, and if so, returns a
  337. pointer to it (this operator does not work with references). If the operand is
  338. not of the correct type, a null pointer is returned. Thus, this works very
  339. much like the <tt>dynamic_cast&lt;&gt;</tt> operator in C++, and should be
  340. used in the same circumstances. Typically, the <tt>dyn_cast&lt;&gt;</tt>
  341. operator is used in an <tt>if</tt> statement or some other flow control
  342. statement like this:</p>
  343. <div class="doc_code">
  344. <pre>
  345. if (<a href="#AllocationInst">AllocationInst</a> *AI = dyn_cast&lt;<a href="#AllocationInst">AllocationInst</a>&gt;(Val)) {
  346. // <i>...</i>
  347. }
  348. </pre>
  349. </div>
  350. <p>This form of the <tt>if</tt> statement effectively combines together a call
  351. to <tt>isa&lt;&gt;</tt> and a call to <tt>cast&lt;&gt;</tt> into one
  352. statement, which is very convenient.</p>
  353. <p>Note that the <tt>dyn_cast&lt;&gt;</tt> operator, like C++'s
  354. <tt>dynamic_cast&lt;&gt;</tt> or Java's <tt>instanceof</tt> operator, can be
  355. abused. In particular, you should not use big chained <tt>if/then/else</tt>
  356. blocks to check for lots of different variants of classes. If you find
  357. yourself wanting to do this, it is much cleaner and more efficient to use the
  358. <tt>InstVisitor</tt> class to dispatch over the instruction type directly.</p>
  359. </dd>
  360. <dt><tt>cast_or_null&lt;&gt;</tt>: </dt>
  361. <dd><p>The <tt>cast_or_null&lt;&gt;</tt> operator works just like the
  362. <tt>cast&lt;&gt;</tt> operator, except that it allows for a null pointer as an
  363. argument (which it then propagates). This can sometimes be useful, allowing
  364. you to combine several null checks into one.</p></dd>
  365. <dt><tt>dyn_cast_or_null&lt;&gt;</tt>: </dt>
  366. <dd><p>The <tt>dyn_cast_or_null&lt;&gt;</tt> operator works just like the
  367. <tt>dyn_cast&lt;&gt;</tt> operator, except that it allows for a null pointer
  368. as an argument (which it then propagates). This can sometimes be useful,
  369. allowing you to combine several null checks into one.</p></dd>
  370. </dl>
  371. <p>These five templates can be used with any classes, whether they have a
  372. v-table or not. To add support for these templates, you simply need to add
  373. <tt>classof</tt> static methods to the class you are interested casting
  374. to. Describing this is currently outside the scope of this document, but there
  375. are lots of examples in the LLVM source base.</p>
  376. </div>
  377. <!-- ======================================================================= -->
  378. <div class="doc_subsection">
  379. <a name="string_apis">Passing strings (the <tt>StringRef</tt>
  380. and <tt>Twine</tt> classes)</a>
  381. </div>
  382. <div class="doc_text">
  383. <p>Although LLVM generally does not do much string manipulation, we do have
  384. several important APIs which take strings. Two important examples are the
  385. Value class -- which has names for instructions, functions, etc. -- and the
  386. StringMap class which is used extensively in LLVM and Clang.</p>
  387. <p>These are generic classes, and they need to be able to accept strings which
  388. may have embedded null characters. Therefore, they cannot simply take
  389. a <tt>const char *</tt>, and taking a <tt>const std::string&amp;</tt> requires
  390. clients to perform a heap allocation which is usually unnecessary. Instead,
  391. many LLVM APIs use a <tt>const StringRef&amp;</tt> or a <tt>const
  392. Twine&amp;</tt> for passing strings efficiently.</p>
  393. </div>
  394. <!-- _______________________________________________________________________ -->
  395. <div class="doc_subsubsection">
  396. <a name="StringRef">The <tt>StringRef</tt> class</a>
  397. </div>
  398. <div class="doc_text">
  399. <p>The <tt>StringRef</tt> data type represents a reference to a constant string
  400. (a character array and a length) and supports the common operations available
  401. on <tt>std:string</tt>, but does not require heap allocation.</p>
  402. <p>It can be implicitly constructed using a C style null-terminated string,
  403. an <tt>std::string</tt>, or explicitly with a character pointer and length.
  404. For example, the <tt>StringRef</tt> find function is declared as:</p>
  405. <div class="doc_code">
  406. iterator find(const StringRef &amp;Key);
  407. </div>
  408. <p>and clients can call it using any one of:</p>
  409. <div class="doc_code">
  410. <pre>
  411. Map.find("foo"); <i>// Lookup "foo"</i>
  412. Map.find(std::string("bar")); <i>// Lookup "bar"</i>
  413. Map.find(StringRef("\0baz", 4)); <i>// Lookup "\0baz"</i>
  414. </pre>
  415. </div>
  416. <p>Similarly, APIs which need to return a string may return a <tt>StringRef</tt>
  417. instance, which can be used directly or converted to an <tt>std::string</tt>
  418. using the <tt>str</tt> member function. See
  419. "<tt><a href="/doxygen/classllvm_1_1StringRef_8h-source.html">llvm/ADT/StringRef.h</a></tt>"
  420. for more information.</p>
  421. <p>You should rarely use the <tt>StringRef</tt> class directly, because it contains
  422. pointers to external memory it is not generally safe to store an instance of the
  423. class (unless you know that the external storage will not be freed).</p>
  424. </div>
  425. <!-- _______________________________________________________________________ -->
  426. <div class="doc_subsubsection">
  427. <a name="Twine">The <tt>Twine</tt> class</a>
  428. </div>
  429. <div class="doc_text">
  430. <p>The <tt>Twine</tt> class is an efficient way for APIs to accept concatenated
  431. strings. For example, a common LLVM paradigm is to name one instruction based on
  432. the name of another instruction with a suffix, for example:</p>
  433. <div class="doc_code">
  434. <pre>
  435. New = CmpInst::Create(<i>...</i>, SO->getName() + ".cmp");
  436. </pre>
  437. </div>
  438. <p>The <tt>Twine</tt> class is effectively a
  439. lightweight <a href="http://en.wikipedia.org/wiki/Rope_(computer_science)">rope</a>
  440. which points to temporary (stack allocated) objects. Twines can be implicitly
  441. constructed as the result of the plus operator applied to strings (i.e., a C
  442. strings, an <tt>std::string</tt>, or a <tt>StringRef</tt>). The twine delays the
  443. actual concatenation of strings until it is actually required, at which point
  444. it can be efficiently rendered directly into a character array. This avoids
  445. unnecessary heap allocation involved in constructing the temporary results of
  446. string concatenation. See
  447. "<tt><a href="/doxygen/classllvm_1_1Twine_8h-source.html">llvm/ADT/Twine.h</a></tt>"
  448. for more information.</p>
  449. <p>As with a <tt>StringRef</tt>, <tt>Twine</tt> objects point to external memory
  450. and should almost never be stored or mentioned directly. They are intended
  451. solely for use when defining a function which should be able to efficiently
  452. accept concatenated strings.</p>
  453. </div>
  454. <!-- ======================================================================= -->
  455. <div class="doc_subsection">
  456. <a name="DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt> option</a>
  457. </div>
  458. <div class="doc_text">
  459. <p>Often when working on your pass you will put a bunch of debugging printouts
  460. and other code into your pass. After you get it working, you want to remove
  461. it, but you may need it again in the future (to work out new bugs that you run
  462. across).</p>
  463. <p> Naturally, because of this, you don't want to delete the debug printouts,
  464. but you don't want them to always be noisy. A standard compromise is to comment
  465. them out, allowing you to enable them if you need them in the future.</p>
  466. <p>The "<tt><a href="/doxygen/Debug_8h-source.html">llvm/Support/Debug.h</a></tt>"
  467. file provides a macro named <tt>DEBUG()</tt> that is a much nicer solution to
  468. this problem. Basically, you can put arbitrary code into the argument of the
  469. <tt>DEBUG</tt> macro, and it is only executed if '<tt>opt</tt>' (or any other
  470. tool) is run with the '<tt>-debug</tt>' command line argument:</p>
  471. <div class="doc_code">
  472. <pre>
  473. DEBUG(errs() &lt;&lt; "I am here!\n");
  474. </pre>
  475. </div>
  476. <p>Then you can run your pass like this:</p>
  477. <div class="doc_code">
  478. <pre>
  479. $ opt &lt; a.bc &gt; /dev/null -mypass
  480. <i>&lt;no output&gt;</i>
  481. $ opt &lt; a.bc &gt; /dev/null -mypass -debug
  482. I am here!
  483. </pre>
  484. </div>
  485. <p>Using the <tt>DEBUG()</tt> macro instead of a home-brewed solution allows you
  486. to not have to create "yet another" command line option for the debug output for
  487. your pass. Note that <tt>DEBUG()</tt> macros are disabled for optimized builds,
  488. so they do not cause a performance impact at all (for the same reason, they
  489. should also not contain side-effects!).</p>
  490. <p>One additional nice thing about the <tt>DEBUG()</tt> macro is that you can
  491. enable or disable it directly in gdb. Just use "<tt>set DebugFlag=0</tt>" or
  492. "<tt>set DebugFlag=1</tt>" from the gdb if the program is running. If the
  493. program hasn't been started yet, you can always just run it with
  494. <tt>-debug</tt>.</p>
  495. </div>
  496. <!-- _______________________________________________________________________ -->
  497. <div class="doc_subsubsection">
  498. <a name="DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt> and
  499. the <tt>-debug-only</tt> option</a>
  500. </div>
  501. <div class="doc_text">
  502. <p>Sometimes you may find yourself in a situation where enabling <tt>-debug</tt>
  503. just turns on <b>too much</b> information (such as when working on the code
  504. generator). If you want to enable debug information with more fine-grained
  505. control, you define the <tt>DEBUG_TYPE</tt> macro and the <tt>-debug</tt> only
  506. option as follows:</p>
  507. <div class="doc_code">
  508. <pre>
  509. #undef DEBUG_TYPE
  510. DEBUG(errs() &lt;&lt; "No debug type\n");
  511. #define DEBUG_TYPE "foo"
  512. DEBUG(errs() &lt;&lt; "'foo' debug type\n");
  513. #undef DEBUG_TYPE
  514. #define DEBUG_TYPE "bar"
  515. DEBUG(errs() &lt;&lt; "'bar' debug type\n"));
  516. #undef DEBUG_TYPE
  517. #define DEBUG_TYPE ""
  518. DEBUG(errs() &lt;&lt; "No debug type (2)\n");
  519. </pre>
  520. </div>
  521. <p>Then you can run your pass like this:</p>
  522. <div class="doc_code">
  523. <pre>
  524. $ opt &lt; a.bc &gt; /dev/null -mypass
  525. <i>&lt;no output&gt;</i>
  526. $ opt &lt; a.bc &gt; /dev/null -mypass -debug
  527. No debug type
  528. 'foo' debug type
  529. 'bar' debug type
  530. No debug type (2)
  531. $ opt &lt; a.bc &gt; /dev/null -mypass -debug-only=foo
  532. 'foo' debug type
  533. $ opt &lt; a.bc &gt; /dev/null -mypass -debug-only=bar
  534. 'bar' debug type
  535. </pre>
  536. </div>
  537. <p>Of course, in practice, you should only set <tt>DEBUG_TYPE</tt> at the top of
  538. a file, to specify the debug type for the entire module (if you do this before
  539. you <tt>#include "llvm/Support/Debug.h"</tt>, you don't have to insert the ugly
  540. <tt>#undef</tt>'s). Also, you should use names more meaningful than "foo" and
  541. "bar", because there is no system in place to ensure that names do not
  542. conflict. If two different modules use the same string, they will all be turned
  543. on when the name is specified. This allows, for example, all debug information
  544. for instruction scheduling to be enabled with <tt>-debug-type=InstrSched</tt>,
  545. even if the source lives in multiple files.</p>
  546. <p>The <tt>DEBUG_WITH_TYPE</tt> macro is also available for situations where you
  547. would like to set <tt>DEBUG_TYPE</tt>, but only for one specific <tt>DEBUG</tt>
  548. statement. It takes an additional first parameter, which is the type to use. For
  549. example, the preceding example could be written as:</p>
  550. <div class="doc_code">
  551. <pre>
  552. DEBUG_WITH_TYPE("", errs() &lt;&lt; "No debug type\n");
  553. DEBUG_WITH_TYPE("foo", errs() &lt;&lt; "'foo' debug type\n");
  554. DEBUG_WITH_TYPE("bar", errs() &lt;&lt; "'bar' debug type\n"));
  555. DEBUG_WITH_TYPE("", errs() &lt;&lt; "No debug type (2)\n");
  556. </pre>
  557. </div>
  558. </div>
  559. <!-- ======================================================================= -->
  560. <div class="doc_subsection">
  561. <a name="Statistic">The <tt>Statistic</tt> class &amp; <tt>-stats</tt>
  562. option</a>
  563. </div>
  564. <div class="doc_text">
  565. <p>The "<tt><a
  566. href="/doxygen/Statistic_8h-source.html">llvm/ADT/Statistic.h</a></tt>" file
  567. provides a class named <tt>Statistic</tt> that is used as a unified way to
  568. keep track of what the LLVM compiler is doing and how effective various
  569. optimizations are. It is useful to see what optimizations are contributing to
  570. making a particular program run faster.</p>
  571. <p>Often you may run your pass on some big program, and you're interested to see
  572. how many times it makes a certain transformation. Although you can do this with
  573. hand inspection, or some ad-hoc method, this is a real pain and not very useful
  574. for big programs. Using the <tt>Statistic</tt> class makes it very easy to
  575. keep track of this information, and the calculated information is presented in a
  576. uniform manner with the rest of the passes being executed.</p>
  577. <p>There are many examples of <tt>Statistic</tt> uses, but the basics of using
  578. it are as follows:</p>
  579. <ol>
  580. <li><p>Define your statistic like this:</p>
  581. <div class="doc_code">
  582. <pre>
  583. #define <a href="#DEBUG_TYPE">DEBUG_TYPE</a> "mypassname" <i>// This goes before any #includes.</i>
  584. STATISTIC(NumXForms, "The # of times I did stuff");
  585. </pre>
  586. </div>
  587. <p>The <tt>STATISTIC</tt> macro defines a static variable, whose name is
  588. specified by the first argument. The pass name is taken from the DEBUG_TYPE
  589. macro, and the description is taken from the second argument. The variable
  590. defined ("NumXForms" in this case) acts like an unsigned integer.</p></li>
  591. <li><p>Whenever you make a transformation, bump the counter:</p>
  592. <div class="doc_code">
  593. <pre>
  594. ++NumXForms; // <i>I did stuff!</i>
  595. </pre>
  596. </div>
  597. </li>
  598. </ol>
  599. <p>That's all you have to do. To get '<tt>opt</tt>' to print out the
  600. statistics gathered, use the '<tt>-stats</tt>' option:</p>
  601. <div class="doc_code">
  602. <pre>
  603. $ opt -stats -mypassname &lt; program.bc &gt; /dev/null
  604. <i>... statistics output ...</i>
  605. </pre>
  606. </div>
  607. <p> When running <tt>opt</tt> on a C file from the SPEC benchmark
  608. suite, it gives a report that looks like this:</p>
  609. <div class="doc_code">
  610. <pre>
  611. 7646 bitcodewriter - Number of normal instructions
  612. 725 bitcodewriter - Number of oversized instructions
  613. 129996 bitcodewriter - Number of bitcode bytes written
  614. 2817 raise - Number of insts DCEd or constprop'd
  615. 3213 raise - Number of cast-of-self removed
  616. 5046 raise - Number of expression trees converted
  617. 75 raise - Number of other getelementptr's formed
  618. 138 raise - Number of load/store peepholes
  619. 42 deadtypeelim - Number of unused typenames removed from symtab
  620. 392 funcresolve - Number of varargs functions resolved
  621. 27 globaldce - Number of global variables removed
  622. 2 adce - Number of basic blocks removed
  623. 134 cee - Number of branches revectored
  624. 49 cee - Number of setcc instruction eliminated
  625. 532 gcse - Number of loads removed
  626. 2919 gcse - Number of instructions removed
  627. 86 indvars - Number of canonical indvars added
  628. 87 indvars - Number of aux indvars removed
  629. 25 instcombine - Number of dead inst eliminate
  630. 434 instcombine - Number of insts combined
  631. 248 licm - Number of load insts hoisted
  632. 1298 licm - Number of insts hoisted to a loop pre-header
  633. 3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
  634. 75 mem2reg - Number of alloca's promoted
  635. 1444 cfgsimplify - Number of blocks simplified
  636. </pre>
  637. </div>
  638. <p>Obviously, with so many optimizations, having a unified framework for this
  639. stuff is very nice. Making your pass fit well into the framework makes it more
  640. maintainable and useful.</p>
  641. </div>
  642. <!-- ======================================================================= -->
  643. <div class="doc_subsection">
  644. <a name="ViewGraph">Viewing graphs while debugging code</a>
  645. </div>
  646. <div class="doc_text">
  647. <p>Several of the important data structures in LLVM are graphs: for example
  648. CFGs made out of LLVM <a href="#BasicBlock">BasicBlock</a>s, CFGs made out of
  649. LLVM <a href="CodeGenerator.html#machinebasicblock">MachineBasicBlock</a>s, and
  650. <a href="CodeGenerator.html#selectiondag_intro">Instruction Selection
  651. DAGs</a>. In many cases, while debugging various parts of the compiler, it is
  652. nice to instantly visualize these graphs.</p>
  653. <p>LLVM provides several callbacks that are available in a debug build to do
  654. exactly that. If you call the <tt>Function::viewCFG()</tt> method, for example,
  655. the current LLVM tool will pop up a window containing the CFG for the function
  656. where each basic block is a node in the graph, and each node contains the
  657. instructions in the block. Similarly, there also exists
  658. <tt>Function::viewCFGOnly()</tt> (does not include the instructions), the
  659. <tt>MachineFunction::viewCFG()</tt> and <tt>MachineFunction::viewCFGOnly()</tt>,
  660. and the <tt>SelectionDAG::viewGraph()</tt> methods. Within GDB, for example,
  661. you can usually use something like <tt>call DAG.viewGraph()</tt> to pop
  662. up a window. Alternatively, you can sprinkle calls to these functions in your
  663. code in places you want to debug.</p>
  664. <p>Getting this to work requires a small amount of configuration. On Unix
  665. systems with X11, install the <a href="http://www.graphviz.org">graphviz</a>
  666. toolkit, and make sure 'dot' and 'gv' are in your path. If you are running on
  667. Mac OS/X, download and install the Mac OS/X <a
  668. href="http://www.pixelglow.com/graphviz/">Graphviz program</a>, and add
  669. <tt>/Applications/Graphviz.app/Contents/MacOS/</tt> (or wherever you install
  670. it) to your path. Once in your system and path are set up, rerun the LLVM
  671. configure script and rebuild LLVM to enable this functionality.</p>
  672. <p><tt>SelectionDAG</tt> has been extended to make it easier to locate
  673. <i>interesting</i> nodes in large complex graphs. From gdb, if you
  674. <tt>call DAG.setGraphColor(<i>node</i>, "<i>color</i>")</tt>, then the
  675. next <tt>call DAG.viewGraph()</tt> would highlight the node in the
  676. specified color (choices of colors can be found at <a
  677. href="http://www.graphviz.org/doc/info/colors.html">colors</a>.) More
  678. complex node attributes can be provided with <tt>call
  679. DAG.setGraphAttrs(<i>node</i>, "<i>attributes</i>")</tt> (choices can be
  680. found at <a href="http://www.graphviz.org/doc/info/attrs.html">Graph
  681. Attributes</a>.) If you want to restart and clear all the current graph
  682. attributes, then you can <tt>call DAG.clearGraphAttrs()</tt>. </p>
  683. </div>
  684. <!-- *********************************************************************** -->
  685. <div class="doc_section">
  686. <a name="datastructure">Picking the Right Data Structure for a Task</a>
  687. </div>
  688. <!-- *********************************************************************** -->
  689. <div class="doc_text">
  690. <p>LLVM has a plethora of data structures in the <tt>llvm/ADT/</tt> directory,
  691. and we commonly use STL data structures. This section describes the trade-offs
  692. you should consider when you pick one.</p>
  693. <p>
  694. The first step is a choose your own adventure: do you want a sequential
  695. container, a set-like container, or a map-like container? The most important
  696. thing when choosing a container is the algorithmic properties of how you plan to
  697. access the container. Based on that, you should use:</p>
  698. <ul>
  699. <li>a <a href="#ds_map">map-like</a> container if you need efficient look-up
  700. of an value based on another value. Map-like containers also support
  701. efficient queries for containment (whether a key is in the map). Map-like
  702. containers generally do not support efficient reverse mapping (values to
  703. keys). If you need that, use two maps. Some map-like containers also
  704. support efficient iteration through the keys in sorted order. Map-like
  705. containers are the most expensive sort, only use them if you need one of
  706. these capabilities.</li>
  707. <li>a <a href="#ds_set">set-like</a> container if you need to put a bunch of
  708. stuff into a container that automatically eliminates duplicates. Some
  709. set-like containers support efficient iteration through the elements in
  710. sorted order. Set-like containers are more expensive than sequential
  711. containers.
  712. </li>
  713. <li>a <a href="#ds_sequential">sequential</a> container provides
  714. the most efficient way to add elements and keeps track of the order they are
  715. added to the collection. They permit duplicates and support efficient
  716. iteration, but do not support efficient look-up based on a key.
  717. </li>
  718. <li>a <a href="#ds_string">string</a> container is a specialized sequential
  719. container or reference structure that is used for character or byte
  720. arrays.</li>
  721. <li>a <a href="#ds_bit">bit</a> container provides an efficient way to store and
  722. perform set operations on sets of numeric id's, while automatically
  723. eliminating duplicates. Bit containers require a maximum of 1 bit for each
  724. identifier you want to store.
  725. </li>
  726. </ul>
  727. <p>
  728. Once the proper category of container is determined, you can fine tune the
  729. memory use, constant factors, and cache behaviors of access by intelligently
  730. picking a member of the category. Note that constant factors and cache behavior
  731. can be a big deal. If you have a vector that usually only contains a few
  732. elements (but could contain many), for example, it's much better to use
  733. <a href="#dss_smallvector">SmallVector</a> than <a href="#dss_vector">vector</a>
  734. . Doing so avoids (relatively) expensive malloc/free calls, which dwarf the
  735. cost of adding the elements to the container. </p>
  736. </div>
  737. <!-- ======================================================================= -->
  738. <div class="doc_subsection">
  739. <a name="ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
  740. </div>
  741. <div class="doc_text">
  742. There are a variety of sequential containers available for you, based on your
  743. needs. Pick the first in this section that will do what you want.
  744. </div>
  745. <!-- _______________________________________________________________________ -->
  746. <div class="doc_subsubsection">
  747. <a name="dss_fixedarrays">Fixed Size Arrays</a>
  748. </div>
  749. <div class="doc_text">
  750. <p>Fixed size arrays are very simple and very fast. They are good if you know
  751. exactly how many elements you have, or you have a (low) upper bound on how many
  752. you have.</p>
  753. </div>
  754. <!-- _______________________________________________________________________ -->
  755. <div class="doc_subsubsection">
  756. <a name="dss_heaparrays">Heap Allocated Arrays</a>
  757. </div>
  758. <div class="doc_text">
  759. <p>Heap allocated arrays (new[] + delete[]) are also simple. They are good if
  760. the number of elements is variable, if you know how many elements you will need
  761. before the array is allocated, and if the array is usually large (if not,
  762. consider a <a href="#dss_smallvector">SmallVector</a>). The cost of a heap
  763. allocated array is the cost of the new/delete (aka malloc/free). Also note that
  764. if you are allocating an array of a type with a constructor, the constructor and
  765. destructors will be run for every element in the array (re-sizable vectors only
  766. construct those elements actually used).</p>
  767. </div>
  768. <!-- _______________________________________________________________________ -->
  769. <div class="doc_subsubsection">
  770. <a name="dss_smallvector">"llvm/ADT/SmallVector.h"</a>
  771. </div>
  772. <div class="doc_text">
  773. <p><tt>SmallVector&lt;Type, N&gt;</tt> is a simple class that looks and smells
  774. just like <tt>vector&lt;Type&gt;</tt>:
  775. it supports efficient iteration, lays out elements in memory order (so you can
  776. do pointer arithmetic between elements), supports efficient push_back/pop_back
  777. operations, supports efficient random access to its elements, etc.</p>
  778. <p>The advantage of SmallVector is that it allocates space for
  779. some number of elements (N) <b>in the object itself</b>. Because of this, if
  780. the SmallVector is dynamically smaller than N, no malloc is performed. This can
  781. be a big win in cases where the malloc/free call is far more expensive than the
  782. code that fiddles around with the elements.</p>
  783. <p>This is good for vectors that are "usually small" (e.g. the number of
  784. predecessors/successors of a block is usually less than 8). On the other hand,
  785. this makes the size of the SmallVector itself large, so you don't want to
  786. allocate lots of them (doing so will waste a lot of space). As such,
  787. SmallVectors are most useful when on the stack.</p>
  788. <p>SmallVector also provides a nice portable and efficient replacement for
  789. <tt>alloca</tt>.</p>
  790. </div>
  791. <!-- _______________________________________________________________________ -->
  792. <div class="doc_subsubsection">
  793. <a name="dss_vector">&lt;vector&gt;</a>
  794. </div>
  795. <div class="doc_text">
  796. <p>
  797. std::vector is well loved and respected. It is useful when SmallVector isn't:
  798. when the size of the vector is often large (thus the small optimization will
  799. rarely be a benefit) or if you will be allocating many instances of the vector
  800. itself (which would waste space for elements that aren't in the container).
  801. vector is also useful when interfacing with code that expects vectors :).
  802. </p>
  803. <p>One worthwhile note about std::vector: avoid code like this:</p>
  804. <div class="doc_code">
  805. <pre>
  806. for ( ... ) {
  807. std::vector&lt;foo&gt; V;
  808. use V;
  809. }
  810. </pre>
  811. </div>
  812. <p>Instead, write this as:</p>
  813. <div class="doc_code">
  814. <pre>
  815. std::vector&lt;foo&gt; V;
  816. for ( ... ) {
  817. use V;
  818. V.clear();
  819. }
  820. </pre>
  821. </div>
  822. <p>Doing so will save (at least) one heap allocation and free per iteration of
  823. the loop.</p>
  824. </div>
  825. <!-- _______________________________________________________________________ -->
  826. <div class="doc_subsubsection">
  827. <a name="dss_deque">&lt;deque&gt;</a>
  828. </div>
  829. <div class="doc_text">
  830. <p>std::deque is, in some senses, a generalized version of std::vector. Like
  831. std::vector, it provides constant time random access and other similar
  832. properties, but it also provides efficient access to the front of the list. It
  833. does not guarantee continuity of elements within memory.</p>
  834. <p>In exchange for this extra flexibility, std::deque has significantly higher
  835. constant factor costs than std::vector. If possible, use std::vector or
  836. something cheaper.</p>
  837. </div>
  838. <!-- _______________________________________________________________________ -->
  839. <div class="doc_subsubsection">
  840. <a name="dss_list">&lt;list&gt;</a>
  841. </div>
  842. <div class="doc_text">
  843. <p>std::list is an extremely inefficient class that is rarely useful.
  844. It performs a heap allocation for every element inserted into it, thus having an
  845. extremely high constant factor, particularly for small data types. std::list
  846. also only supports bidirectional iteration, not random access iteration.</p>
  847. <p>In exchange for this high cost, std::list supports efficient access to both
  848. ends of the list (like std::deque, but unlike std::vector or SmallVector). In
  849. addition, the iterator invalidation characteristics of std::list are stronger
  850. than that of a vector class: inserting or removing an element into the list does
  851. not invalidate iterator or pointers to other elements in the list.</p>
  852. </div>
  853. <!-- _______________________________________________________________________ -->
  854. <div class="doc_subsubsection">
  855. <a name="dss_ilist">llvm/ADT/ilist.h</a>
  856. </div>
  857. <div class="doc_text">
  858. <p><tt>ilist&lt;T&gt;</tt> implements an 'intrusive' doubly-linked list. It is
  859. intrusive, because it requires the element to store and provide access to the
  860. prev/next pointers for the list.</p>
  861. <p><tt>ilist</tt> has the same drawbacks as <tt>std::list</tt>, and additionally
  862. requires an <tt>ilist_traits</tt> implementation for the element type, but it
  863. provides some novel characteristics. In particular, it can efficiently store
  864. polymorphic objects, the traits class is informed when an element is inserted or
  865. removed from the list, and <tt>ilist</tt>s are guaranteed to support a
  866. constant-time splice operation.</p>
  867. <p>These properties are exactly what we want for things like
  868. <tt>Instruction</tt>s and basic blocks, which is why these are implemented with
  869. <tt>ilist</tt>s.</p>
  870. Related classes of interest are explained in the following subsections:
  871. <ul>
  872. <li><a href="#dss_ilist_traits">ilist_traits</a></li>
  873. <li><a href="#dss_iplist">iplist</a></li>
  874. <li><a href="#dss_ilist_node">llvm/ADT/ilist_node.h</a></li>
  875. <li><a href="#dss_ilist_sentinel">Sentinels</a></li>
  876. </ul>
  877. </div>
  878. <!-- _______________________________________________________________________ -->
  879. <div class="doc_subsubsection">
  880. <a name="dss_ilist_traits">ilist_traits</a>
  881. </div>
  882. <div class="doc_text">
  883. <p><tt>ilist_traits&lt;T&gt;</tt> is <tt>ilist&lt;T&gt;</tt>'s customization
  884. mechanism. <tt>iplist&lt;T&gt;</tt> (and consequently <tt>ilist&lt;T&gt;</tt>)
  885. publicly derive from this traits class.</p>
  886. </div>
  887. <!-- _______________________________________________________________________ -->
  888. <div class="doc_subsubsection">
  889. <a name="dss_iplist">iplist</a>
  890. </div>
  891. <div class="doc_text">
  892. <p><tt>iplist&lt;T&gt;</tt> is <tt>ilist&lt;T&gt;</tt>'s base and as such
  893. supports a slightly narrower interface. Notably, inserters from
  894. <tt>T&amp;</tt> are absent.</p>
  895. <p><tt>ilist_traits&lt;T&gt;</tt> is a public base of this class and can be
  896. used for a wide variety of customizations.</p>
  897. </div>
  898. <!-- _______________________________________________________________________ -->
  899. <div class="doc_subsubsection">
  900. <a name="dss_ilist_node">llvm/ADT/ilist_node.h</a>
  901. </div>
  902. <div class="doc_text">
  903. <p><tt>ilist_node&lt;T&gt;</tt> implements a the forward and backward links
  904. that are expected by the <tt>ilist&lt;T&gt;</tt> (and analogous containers)
  905. in the default manner.</p>
  906. <p><tt>ilist_node&lt;T&gt;</tt>s are meant to be embedded in the node type
  907. <tt>T</tt>, usually <tt>T</tt> publicly derives from
  908. <tt>ilist_node&lt;T&gt;</tt>.</p>
  909. </div>
  910. <!-- _______________________________________________________________________ -->
  911. <div class="doc_subsubsection">
  912. <a name="dss_ilist_sentinel">Sentinels</a>
  913. </div>
  914. <div class="doc_text">
  915. <p><tt>ilist</tt>s have another specialty that must be considered. To be a good
  916. citizen in the C++ ecosystem, it needs to support the standard container
  917. operations, such as <tt>begin</tt> and <tt>end</tt> iterators, etc. Also, the
  918. <tt>operator--</tt> must work correctly on the <tt>end</tt> iterator in the
  919. case of non-empty <tt>ilist</tt>s.</p>
  920. <p>The only sensible solution to this problem is to allocate a so-called
  921. <i>sentinel</i> along with the intrusive list, which serves as the <tt>end</tt>
  922. iterator, providing the back-link to the last element. However conforming to the
  923. C++ convention it is illegal to <tt>operator++</tt> beyond the sentinel and it
  924. also must not be dereferenced.</p>
  925. <p>These constraints allow for some implementation freedom to the <tt>ilist</tt>
  926. how to allocate and store the sentinel. The corresponding policy is dictated
  927. by <tt>ilist_traits&lt;T&gt;</tt>. By default a <tt>T</tt> gets heap-allocated
  928. whenever the need for a sentinel arises.</p>
  929. <p>While the default policy is sufficient in most cases, it may break down when
  930. <tt>T</tt> does not provide a default constructor. Also, in the case of many
  931. instances of <tt>ilist</tt>s, the memory overhead of the associated sentinels
  932. is wasted. To alleviate the situation with numerous and voluminous
  933. <tt>T</tt>-sentinels, sometimes a trick is employed, leading to <i>ghostly
  934. sentinels</i>.</p>
  935. <p>Ghostly sentinels are obtained by specially-crafted <tt>ilist_traits&lt;T&gt;</tt>
  936. which superpose the sentinel with the <tt>ilist</tt> instance in memory. Pointer
  937. arithmetic is used to obtain the sentinel, which is relative to the
  938. <tt>ilist</tt>'s <tt>this</tt> pointer. The <tt>ilist</tt> is augmented by an
  939. extra pointer, which serves as the back-link of the sentinel. This is the only
  940. field in the ghostly sentinel which can be legally accessed.</p>
  941. </div>
  942. <!-- _______________________________________________________________________ -->
  943. <div class="doc_subsubsection">
  944. <a name="dss_other">Other Sequential Container options</a>
  945. </div>
  946. <div class="doc_text">
  947. <p>Other STL containers are available, such as std::string.</p>
  948. <p>There are also various STL adapter classes such as std::queue,
  949. std::priority_queue, std::stack, etc. These provide simplified access to an
  950. underlying container but don't affect the cost of the container itself.</p>
  951. </div>
  952. <!-- ======================================================================= -->
  953. <div class="doc_subsection">
  954. <a name="ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
  955. </div>
  956. <div class="doc_text">
  957. <p>Set-like containers are useful when you need to canonicalize multiple values
  958. into a single representation. There are several different choices for how to do
  959. this, providing various trade-offs.</p>
  960. </div>
  961. <!-- _______________________________________________________________________ -->
  962. <div class="doc_subsubsection">
  963. <a name="dss_sortedvectorset">A sorted 'vector'</a>
  964. </div>
  965. <div class="doc_text">
  966. <p>If you intend to insert a lot of elements, then do a lot of queries, a
  967. great approach is to use a vector (or other sequential container) with
  968. std::sort+std::unique to remove duplicates. This approach works really well if
  969. your usage pattern has these two distinct phases (insert then query), and can be
  970. coupled with a good choice of <a href="#ds_sequential">sequential container</a>.
  971. </p>
  972. <p>
  973. This combination provides the several nice properties: the result data is
  974. contiguous in memory (good for cache locality), has few allocations, is easy to
  975. address (iterators in the final vector are just indices or pointers), and can be
  976. efficiently queried with a standard binary or radix search.</p>
  977. </div>
  978. <!-- _______________________________________________________________________ -->
  979. <div class="doc_subsubsection">
  980. <a name="dss_smallset">"llvm/ADT/SmallSet.h"</a>
  981. </div>
  982. <div class="doc_text">
  983. <p>If you have a set-like data structure that is usually small and whose elements
  984. are reasonably small, a <tt>SmallSet&lt;Type, N&gt;</tt> is a good choice. This set
  985. has space for N elements in place (thus, if the set is dynamically smaller than
  986. N, no malloc traffic is required) and accesses them with a simple linear search.
  987. When the set grows beyond 'N' elements, it allocates a more expensive representation that
  988. guarantees efficient access (for most types, it falls back to std::set, but for
  989. pointers it uses something far better, <a
  990. href="#dss_smallptrset">SmallPtrSet</a>).</p>
  991. <p>The magic of this class is that it handles small sets extremely efficiently,
  992. but gracefully handles extremely large sets without loss of efficiency. The
  993. drawback is that the interface is quite small: it supports insertion, queries
  994. and erasing, but does not support iteration.</p>
  995. </div>
  996. <!-- _______________________________________________________________________ -->
  997. <div class="doc_subsubsection">
  998. <a name="dss_smallptrset">"llvm/ADT/SmallPtrSet.h"</a>
  999. </div>
  1000. <div class="doc_text">
  1001. <p>SmallPtrSet has all the advantages of <tt>SmallSet</tt> (and a <tt>SmallSet</tt> of pointers is
  1002. transparently implemented with a <tt>SmallPtrSet</tt>), but also supports iterators. If
  1003. more than 'N' insertions are performed, a single quadratically
  1004. probed hash table is allocated and grows as needed, providing extremely
  1005. efficient access (constant time insertion/deleting/queries with low constant
  1006. factors) and is very stingy with malloc traffic.</p>
  1007. <p>Note that, unlike <tt>std::set</tt>, the iterators of <tt>SmallPtrSet</tt> are invalidated
  1008. whenever an insertion occurs. Also, the values visited by the iterators are not
  1009. visited in sorted order.</p>
  1010. </div>
  1011. <!-- _______________________________________________________________________ -->
  1012. <div class="doc_subsubsection">
  1013. <a name="dss_denseset">"llvm/ADT/DenseSet.h"</a>
  1014. </div>
  1015. <div class="doc_text">
  1016. <p>
  1017. DenseSet is a simple quadratically probed hash table. It excels at supporting
  1018. small values: it uses a single allocation to hold all of the pairs that
  1019. are currently inserted in the set. DenseSet is a great way to unique small
  1020. values that are not simple pointers (use <a
  1021. href="#dss_smallptrset">SmallPtrSet</a> for pointers). Note that DenseSet has
  1022. the same requirements for the value type that <a
  1023. href="#dss_densemap">DenseMap</a> has.
  1024. </p>
  1025. </div>
  1026. <!-- _______________________________________________________________________ -->
  1027. <div class="doc_subsubsection">
  1028. <a name="dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a>
  1029. </div>
  1030. <div class="doc_text">
  1031. <p>
  1032. FoldingSet is an aggregate class that is really good at uniquing
  1033. expensive-to-create or polymorphic objects. It is a combination of a chained
  1034. hash table with intrusive links (uniqued objects are required to inherit from
  1035. FoldingSetNode) that uses <a href="#dss_smallvector">SmallVector</a> as part of
  1036. its ID process.</p>
  1037. <p>Consider a case where you want to implement a "getOrCreateFoo" method for
  1038. a complex object (for example, a node in the code generator). The client has a
  1039. description of *what* it wants to generate (it knows the opcode and all the
  1040. operands), but we don't want to 'new' a node, then try inserting it into a set
  1041. only to find out it already exists, at which point we would have to delete it
  1042. and return the node that already exists.
  1043. </p>
  1044. <p>To support this style of client, FoldingSet perform a query with a
  1045. FoldingSetNodeID (which wraps SmallVector) that can be used to describe the
  1046. element that we want to query for. The query either returns the element
  1047. matching the ID or it returns an opaque ID that indicates where insertion should
  1048. take place. Construction of the ID usually does not require heap traffic.</p>
  1049. <p>Because FoldingSet uses intrusive links, it can support polymorphic objects
  1050. in the set (for example, you can have SDNode instances mixed with LoadSDNodes).
  1051. Because the elements are individually allocated, pointers to the elements are
  1052. stable: inserting or removing elements does not invalidate any pointers to other
  1053. elements.
  1054. </p>
  1055. </div>
  1056. <!-- _______________________________________________________________________ -->
  1057. <div class="doc_subsubsection">
  1058. <a name="dss_set">&lt;set&gt;</a>
  1059. </div>
  1060. <div class="doc_text">
  1061. <p><tt>std::set</tt> is a reasonable all-around set class, which is decent at
  1062. many things but great at nothing. std::set allocates memory for each element
  1063. inserted (thus it is very malloc intensive) and typically stores three pointers
  1064. per element in the set (thus adding a large amount of per-element space
  1065. overhead). It offers guaranteed log(n) performance, which is not particularly
  1066. fast from a complexity standpoint (particularly if the elements of the set are
  1067. expensive to compare, like strings), and has extremely high constant factors for
  1068. lookup, insertion and removal.</p>
  1069. <p>The advantages of std::set are that its iterators are stable (deleting or
  1070. inserting an element from the set does not affect iterators or pointers to other
  1071. elements) and that iteration over the set is guaranteed to be in sorted order.
  1072. If the elements in the set are large, then the relative overhead of the pointers
  1073. and malloc traffic is not a big deal, but if the elements of the set are small,
  1074. std::set is almost never a good choice.</p>
  1075. </div>
  1076. <!-- _______________________________________________________________________ -->
  1077. <div class="doc_subsubsection">
  1078. <a name="dss_setvector">"llvm/ADT/SetVector.h"</a>
  1079. </div>
  1080. <div class="doc_text">
  1081. <p>LLVM's SetVector&lt;Type&gt; is an adapter class that combines your choice of
  1082. a set-like container along with a <a href="#ds_sequential">Sequential
  1083. Container</a>. The important property
  1084. that this provides is efficient insertion with uniquing (duplicate elements are
  1085. ignored) with iteration support. It implements this by inserting elements into
  1086. both a set-like container and the sequential container, using the set-like
  1087. container for uniquing and the sequential container for iteration.
  1088. </p>
  1089. <p>The difference between SetVector and other sets is that the order of
  1090. iteration is guaranteed to match the order of insertion into the SetVector.
  1091. This property is really important for things like sets of pointers. Because
  1092. pointer values are non-deterministic (e.g. vary across runs of the program on
  1093. different machines), iterating over the pointers in the set will
  1094. not be in a well-defined order.</p>
  1095. <p>
  1096. The drawback of SetVector is that it requires twice as much space as a normal
  1097. set and has the sum of constant factors from the set-like container and the
  1098. sequential container that it uses. Use it *only* if you need to iterate over
  1099. the elements in a deterministic order. SetVector is also expensive to delete
  1100. elements out of (linear time), unless you use it's "pop_back" method, which is
  1101. faster.
  1102. </p>
  1103. <p>SetVector is an adapter class that defaults to using std::vector and std::set
  1104. for the underlying containers, so it is quite expensive. However,
  1105. <tt>"llvm/ADT/SetVector.h"</tt> also provides a SmallSetVector class, which
  1106. defaults to using a SmallVector and SmallSet of a specified size. If you use
  1107. this, and if your sets are dynamically smaller than N, you will save a lot of
  1108. heap traffic.</p>
  1109. </div>
  1110. <!-- _______________________________________________________________________ -->
  1111. <div class="doc_subsubsection">
  1112. <a name="dss_uniquevector">"llvm/ADT/UniqueVector.h"</a>
  1113. </div>
  1114. <div class="doc_text">
  1115. <p>
  1116. UniqueVector is similar to <a href="#dss_setvector">SetVector</a>, but it
  1117. retains a unique ID for each element inserted into the set. It internally
  1118. contains a map and a vector, and it assigns a unique ID for each value inserted
  1119. into the set.</p>
  1120. <p>UniqueVector is very expensive: its cost is the sum of the cost of
  1121. maintaining both the map and vector, it has high complexity, high constant
  1122. factors, and produces a lot of malloc traffic. It should be avoided.</p>
  1123. </div>
  1124. <!-- _______________________________________________________________________ -->
  1125. <div class="doc_subsubsection">
  1126. <a name="dss_otherset">Other Set-Like Container Options</a>
  1127. </div>
  1128. <div class="doc_text">
  1129. <p>
  1130. The STL provides several other options, such as std::multiset and the various
  1131. "hash_set" like containers (whether from C++ TR1 or from the SGI library). We
  1132. never use hash_set and unordered_set because they are generally very expensive
  1133. (each insertion requires a malloc) and very non-portable.
  1134. </p>
  1135. <p>std::multiset is useful if you're not interested in elimination of
  1136. duplicates, but has all the drawbacks of std::set. A sorted vector (where you
  1137. don't delete duplicate entries) or some other approach is almost always
  1138. better.</p>
  1139. </div>
  1140. <!-- ======================================================================= -->
  1141. <div class="doc_subsection">
  1142. <a name="ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
  1143. </div>
  1144. <div class="doc_text">
  1145. Map-like containers are useful when you want to associate data to a key. As
  1146. usual, there are a lot of different ways to do this. :)
  1147. </div>
  1148. <!-- _______________________________________________________________________ -->
  1149. <div class="doc_subsubsection">
  1150. <a name="dss_sortedvectormap">A sorted 'vector'</a>
  1151. </div>
  1152. <div class="doc_text">
  1153. <p>
  1154. If your usage pattern follows a strict insert-then-query approach, you can
  1155. trivially use the same approach as <a href="#dss_sortedvectorset">sorted vectors
  1156. for set-like containers</a>. The only difference is that your query function
  1157. (which uses std::lower_bound to get efficient log(n) lookup) should only compare
  1158. the key, not both the key and value. This yields the same advantages as sorted
  1159. vectors for sets.
  1160. </p>
  1161. </div>
  1162. <!-- _______________________________________________________________________ -->
  1163. <div class="doc_subsubsection">
  1164. <a name="dss_stringmap">"llvm/ADT/StringMap.h"</a>
  1165. </div>
  1166. <div class="doc_text">
  1167. <p>
  1168. Strings are commonly used as keys in maps, and they are difficult to support
  1169. efficiently: they are variable length, inefficient to hash and compare when
  1170. long, expensive to copy, etc. StringMap is a specialized container designed to
  1171. cope with these issues. It supports mapping an arbitrary range of bytes to an
  1172. arbitrary other object.</p>
  1173. <p>The StringMap implementation uses a quadratically-probed hash table, where
  1174. the buckets store a pointer to the heap allocated entries (and some other
  1175. stuff). The entries in the map must be heap allocated because the strings are
  1176. variable length. The string data (key) and the element object (value) are
  1177. stored in the same allocation with the string data immediately after the element
  1178. object. This container guarantees the "<tt>(char*)(&amp;Value+1)</tt>" points
  1179. to the key string for a value.</p>
  1180. <p>The StringMap is very fast for several reasons: quadratic probing is very
  1181. cache efficient for lookups, the hash value of strings in buckets is not
  1182. recomputed when lookup up an element, StringMap rarely has to touch the
  1183. memory for unrelated objects when looking up a value (even when hash collisions
  1184. happen), hash table growth does not recompute the hash values for strings
  1185. already in the table, and each pair in the map is store in a single allocation
  1186. (the string data is stored in the same allocation as the Value of a pair).</p>
  1187. <p>StringMap also provides query methods that take byte ranges, so it only ever
  1188. copies a string if a value is inserted into the table.</p>
  1189. </div>
  1190. <!-- _______________________________________________________________________ -->
  1191. <div class="doc_subsubsection">
  1192. <a name="dss_indexedmap">"llvm/ADT/IndexedMap.h"</a>
  1193. </div>
  1194. <div class="doc_text">
  1195. <p>
  1196. IndexedMap is a specialized container for mapping small dense integers (or
  1197. values that can be mapped to small dense integers) to some other type. It is
  1198. internally implemented as a vector with a mapping function that maps the keys to
  1199. the dense integer range.
  1200. </p>
  1201. <p>
  1202. This is useful for cases like virtual registers in the LLVM code generator: they
  1203. have a dense mapping that is offset by a compile-time constant (the first
  1204. virtual register ID).</p>
  1205. </div>
  1206. <!-- _______________________________________________________________________ -->
  1207. <div class="doc_subsubsection">
  1208. <a name="dss_densemap">"llvm/ADT/DenseMap.h"</a>
  1209. </div>
  1210. <div class="doc_text">
  1211. <p>
  1212. DenseMap is a simple quadratically probed hash table. It excels at supporting
  1213. small keys and values: it uses a single allocation to hold all of the pairs that
  1214. are currently inserted in the map. DenseMap is a great way to map pointers to
  1215. pointers, or map other small types to each other.
  1216. </p>
  1217. <p>
  1218. There are several aspects of DenseMap that you should be aware of, however. The
  1219. iterators in a densemap are invalidated whenever an insertion occurs, unlike
  1220. map. Also, because DenseMap allocates space for a large number of key/value
  1221. pairs (it starts with 64 by default), it will waste a lot of space if your keys
  1222. or values are large. Finally, you must implement a partial specialization of
  1223. DenseMapInfo for the key that you want, if it isn't already supported. This
  1224. is required to tell DenseMap about two special marker values (which can never be
  1225. inserted into the map) that it needs internally.</p>
  1226. </div>
  1227. <!-- _______________________________________________________________________ -->
  1228. <div class="doc_subsubsection">
  1229. <a name="dss_valuemap">"llvm/ADT/ValueMap.h"</a>
  1230. </div>
  1231. <div class="doc_text">
  1232. <p>
  1233. ValueMap is a wrapper around a <a href="#dss_densemap">DenseMap</a> mapping
  1234. Value*s (or subclasses) to another type. When a Value is deleted or RAUW'ed,
  1235. ValueMap will update itself so the new version of the key is mapped to the same
  1236. value, just as if the key were a WeakVH. You can configure exactly how this
  1237. happens, and what else happens on these two events, by passing
  1238. a <code>Config</code> parameter to the ValueMap template.</p>
  1239. </div>
  1240. <!-- _______________________________________________________________________ -->
  1241. <div class="doc_subsubsection">
  1242. <a name="dss_map">&lt;map&gt;</a>
  1243. </div>
  1244. <div class="doc_text">
  1245. <p>
  1246. std::map has similar characteristics to <a href="#dss_set">std::set</a>: it uses
  1247. a single allocation per pair inserted into the map, it offers log(n) lookup with
  1248. an extremely large constant factor, imposes a space penalty of 3 pointers per
  1249. pair in the map, etc.</p>
  1250. <p>std::map is most useful when your keys or values are very large, if you need
  1251. to iterate over the collection in sorted order, or if you need stable iterators
  1252. into the map (i.e. they don't get invalidated if an insertion or deletion of
  1253. another element takes place).</p>
  1254. </div>
  1255. <!-- _______________________________________________________________________ -->
  1256. <div class="doc_subsubsection">
  1257. <a name="dss_othermap">Other Map-Like Container Options</a>
  1258. </div>
  1259. <div class="doc_text">
  1260. <p>
  1261. The STL provides several other options, such as std::multimap and the various
  1262. "hash_map" like containers (whether from C++ TR1 or from the SGI library). We
  1263. never use hash_set and unordered_set because they are generally very expensive
  1264. (each insertion requires a malloc) and very non-portable.</p>
  1265. <p>std::multimap is useful if you want to map a key to multiple values, but has
  1266. all the drawbacks of std::map. A sorted vector or some other approach is almost
  1267. always better.</p>
  1268. </div>
  1269. <!-- ======================================================================= -->
  1270. <div class="doc_subsection">
  1271. <a name="ds_string">String-like containers</a>
  1272. </div>
  1273. <div class="doc_text">
  1274. <p>
  1275. TODO: const char* vs stringref vs smallstring vs std::string. Describe twine,
  1276. xref to #string_apis.
  1277. </p>
  1278. </div>
  1279. <!-- ======================================================================= -->
  1280. <div class="doc_subsection">
  1281. <a name="ds_bit">Bit storage containers (BitVector, SparseBitVector)</a>
  1282. </div>
  1283. <div class="doc_text">
  1284. <p>Unlike the other containers, there are only two bit storage containers, and
  1285. choosing when to use each is relatively straightforward.</p>
  1286. <p>One additional option is
  1287. <tt>std::vector&lt;bool&gt;</tt>: we discourage its use for two reasons 1) the
  1288. implementation in many common compilers (e.g. commonly available versions of
  1289. GCC) is extremely inefficient and 2) the C++ standards committee is likely to
  1290. deprecate this container and/or change it significantly somehow. In any case,
  1291. please don't use it.</p>
  1292. </div>
  1293. <!-- _______________________________________________________________________ -->
  1294. <div class="doc_subsubsection">
  1295. <a name="dss_bitvector">BitVector</a>
  1296. </div>
  1297. <div class="doc_text">
  1298. <p> The BitVector container provides a dynamic size set of bits for manipulation.
  1299. It supports individual bit setting/testing, as well as set operations. The set
  1300. operations take time O(size of bitvector), but operations are performed one word
  1301. at a time, instead of one bit at a time. This makes the BitVector very fast for
  1302. set operations compared to other containers. Use the BitVector when you expect
  1303. the number of set bits to be high (IE a dense set).
  1304. </p>
  1305. </div>
  1306. <!-- _______________________________________________________________________ -->
  1307. <div class="doc_subsubsection">
  1308. <a name="dss_smallbitvector">SmallBitVector</a>
  1309. </div>
  1310. <div class="doc_text">
  1311. <p> The SmallBitVector container provides the same interface as BitVector, but
  1312. it is optimized for the case where only a small number of bits, less than
  1313. 25 or so, are needed. It also transparently supports larger bit counts, but
  1314. slightly less efficiently than a plain BitVector, so SmallBitVector should
  1315. only be used when larger counts are rare.
  1316. </p>
  1317. <p>
  1318. At this time, SmallBitVector does not support set operations (and, or, xor),
  1319. and its operator[] does not provide an assignable lvalue.
  1320. </p>
  1321. </div>
  1322. <!-- _______________________________________________________________________ -->
  1323. <div class="doc_subsubsection">
  1324. <a name="dss_sparsebitvector">SparseBitVector</a>
  1325. </div>
  1326. <div class="doc_text">
  1327. <p> The SparseBitVector container is much like BitVector, with one major
  1328. difference: Only the bits that are set, are stored. This makes the
  1329. SparseBitVector much more space efficient than BitVector when the set is sparse,
  1330. as well as making set operations O(number of set bits) instead of O(size of
  1331. universe). The downside to the SparseBitVector is that setting and testing of random bits is O(N), and on large SparseBitVectors, this can be slower than BitVector. In our implementation, setting or testing bits in sorted order
  1332. (either forwards or reverse) is O(1) worst case. Testing and setting bits within 128 bits (depends on size) of the current bit is also O(1). As a general statement, testing/setting bits in a SparseBitVector is O(distance away from last set bit).
  1333. </p>
  1334. </div>
  1335. <!-- *********************************************************************** -->
  1336. <div class="doc_section">
  1337. <a name="common">Helpful Hints for Common Operations</a>
  1338. </div>
  1339. <!-- *********************************************************************** -->
  1340. <div class="doc_text">
  1341. <p>This section describes how to perform some very simple transformations of
  1342. LLVM code. This is meant to give examples of common idioms used, showing the
  1343. practical side of LLVM transformations. <p> Because this is a "how-to" section,
  1344. you should also read about the main classes that you will be working with. The
  1345. <a href="#coreclasses">Core LLVM Class Hierarchy Reference</a> contains details
  1346. and descriptions of the main classes that you should know about.</p>
  1347. </div>
  1348. <!-- NOTE: this section should be heavy on example code -->
  1349. <!-- ======================================================================= -->
  1350. <div class="doc_subsection">
  1351. <a name="inspection">Basic Inspection and Traversal Routines</a>
  1352. </div>
  1353. <div class="doc_text">
  1354. <p>The LLVM compiler infrastructure have many different data structures that may
  1355. be traversed. Following the example of the C++ standard template library, the
  1356. techniques used to traverse these various data structures are all basically the
  1357. same. For a enumerable sequence of values, the <tt>XXXbegin()</tt> function (or
  1358. method) returns an iterator to the start of the sequence, the <tt>XXXend()</tt>
  1359. function returns an iterator pointing to one past the last valid element of the
  1360. sequence, and there is some <tt>XXXiterator</tt> data type that is common
  1361. between the two operations.</p>
  1362. <p>Because the pattern for iteration is common across many different aspects of
  1363. the program representation, the standard template library algorithms may be used
  1364. on them, and it is easier to remember how to iterate. First we show a few common
  1365. examples of the data structures that need to be traversed. Other data
  1366. structures are traversed in very similar ways.</p>
  1367. </div>
  1368. <!-- _______________________________________________________________________ -->
  1369. <div class="doc_subsubsection">
  1370. <a name="iterate_function">Iterating over the </a><a
  1371. href="#BasicBlock"><tt>BasicBlock</tt></a>s in a <a
  1372. href="#Function"><tt>Function</tt></a>
  1373. </div>
  1374. <div class="doc_text">
  1375. <p>It's quite common to have a <tt>Function</tt> instance that you'd like to
  1376. transform in some way; in particular, you'd like to manipulate its
  1377. <tt>BasicBlock</tt>s. To facilitate this, you'll need to iterate over all of
  1378. the <tt>BasicBlock</tt>s that constitute the <tt>Function</tt>. The following is
  1379. an example that prints the name of a <tt>BasicBlock</tt> and the number of
  1380. <tt>Instruction</tt>s it contains:</p>
  1381. <div class="doc_code">
  1382. <pre>
  1383. // <i>func is a pointer to a Function instance</i>
  1384. for (Function::iterator i = func-&gt;begin(), e = func-&gt;end(); i != e; ++i)
  1385. // <i>Print out the name of the basic block if it has one, and then the</i>
  1386. // <i>number of instructions that it contains</i>
  1387. errs() &lt;&lt; "Basic block (name=" &lt;&lt; i-&gt;getName() &lt;&lt; ") has "
  1388. &lt;&lt; i-&gt;size() &lt;&lt; " instructions.\n";
  1389. </pre>
  1390. </div>
  1391. <p>Note that i can be used as if it were a pointer for the purposes of
  1392. invoking member functions of the <tt>Instruction</tt> class. This is
  1393. because the indirection operator is overloaded for the iterator
  1394. classes. In the above code, the expression <tt>i-&gt;size()</tt> is
  1395. exactly equivalent to <tt>(*i).size()</tt> just like you'd expect.</p>
  1396. </div>
  1397. <!-- _______________________________________________________________________ -->
  1398. <div class="doc_subsubsection">
  1399. <a name="iterate_basicblock">Iterating over the </a><a
  1400. href="#Instruction"><tt>Instruction</tt></a>s in a <a
  1401. href="#BasicBlock"><tt>BasicBlock</tt></a>
  1402. </div>
  1403. <div class="doc_text">
  1404. <p>Just like when dealing with <tt>BasicBlock</tt>s in <tt>Function</tt>s, it's
  1405. easy to iterate over the individual instructions that make up
  1406. <tt>BasicBlock</tt>s. Here's a code snippet that prints out each instruction in
  1407. a <tt>BasicBlock</tt>:</p>
  1408. <div class="doc_code">
  1409. <pre>
  1410. // <i>blk is a pointer to a BasicBlock instance</i>
  1411. for (BasicBlock::iterator i = blk-&gt;begin(), e = blk-&gt;end(); i != e; ++i)
  1412. // <i>The next statement works since operator&lt;&lt;(ostream&amp;,...)</i>
  1413. // <i>is overloaded for Instruction&amp;</i>
  1414. errs() &lt;&lt; *i &lt;&lt; "\n";
  1415. </pre>
  1416. </div>
  1417. <p>However, this isn't really the best way to print out the contents of a
  1418. <tt>BasicBlock</tt>! Since the ostream operators are overloaded for virtually
  1419. anything you'll care about, you could have just invoked the print routine on the
  1420. basic block itself: <tt>errs() &lt;&lt; *blk &lt;&lt; "\n";</tt>.</p>
  1421. </div>
  1422. <!-- _______________________________________________________________________ -->
  1423. <div class="doc_subsubsection">
  1424. <a name="iterate_institer">Iterating over the </a><a
  1425. href="#Instruction"><tt>Instruction</tt></a>s in a <a
  1426. href="#Function"><tt>Function</tt></a>
  1427. </div>
  1428. <div class="doc_text">
  1429. <p>If you're finding that you commonly iterate over a <tt>Function</tt>'s
  1430. <tt>BasicBlock</tt>s and then that <tt>BasicBlock</tt>'s <tt>Instruction</tt>s,
  1431. <tt>InstIterator</tt> should be used instead. You'll need to include <a
  1432. href="/doxygen/InstIterator_8h-source.html"><tt>llvm/Support/InstIterator.h</tt></a>,
  1433. and then instantiate <tt>InstIterator</tt>s explicitly in your code. Here's a
  1434. small example that shows how to dump all instructions in a function to the standard error stream:<p>
  1435. <div class="doc_code">
  1436. <pre>
  1437. #include "<a href="/doxygen/InstIterator_8h-source.html">llvm/Support/InstIterator.h</a>"
  1438. // <i>F is a pointer to a Function instance</i>
  1439. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
  1440. errs() &lt;&lt; *I &lt;&lt; "\n";
  1441. </pre>
  1442. </div>
  1443. <p>Easy, isn't it? You can also use <tt>InstIterator</tt>s to fill a
  1444. work list with its initial contents. For example, if you wanted to
  1445. initialize a work list to contain all instructions in a <tt>Function</tt>
  1446. F, all you would need to do is something like:</p>
  1447. <div class="doc_code">
  1448. <pre>
  1449. std::set&lt;Instruction*&gt; worklist;
  1450. // or better yet, SmallPtrSet&lt;Instruction*, 64&gt; worklist;
  1451. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
  1452. worklist.insert(&amp;*I);
  1453. </pre>
  1454. </div>
  1455. <p>The STL set <tt>worklist</tt> would now contain all instructions in the
  1456. <tt>Function</tt> pointed to by F.</p>
  1457. </div>
  1458. <!-- _______________________________________________________________________ -->
  1459. <div class="doc_subsubsection">
  1460. <a name="iterate_convert">Turning an iterator into a class pointer (and
  1461. vice-versa)</a>
  1462. </div>
  1463. <div class="doc_text">
  1464. <p>Sometimes, it'll be useful to grab a reference (or pointer) to a class
  1465. instance when all you've got at hand is an iterator. Well, extracting
  1466. a reference or a pointer from an iterator is very straight-forward.
  1467. Assuming that <tt>i</tt> is a <tt>BasicBlock::iterator</tt> and <tt>j</tt>
  1468. is a <tt>BasicBlock::const_iterator</tt>:</p>
  1469. <div class="doc_code">
  1470. <pre>
  1471. Instruction&amp; inst = *i; // <i>Grab reference to instruction reference</i>
  1472. Instruction* pinst = &amp;*i; // <i>Grab pointer to instruction reference</i>
  1473. const Instruction&amp; inst = *j;
  1474. </pre>
  1475. </div>
  1476. <p>However, the iterators you'll be working with in the LLVM framework are
  1477. special: they will automatically convert to a ptr-to-instance type whenever they
  1478. need to. Instead of dereferencing the iterator and then taking the address of
  1479. the result, you can simply assign the iterator to the proper pointer type and
  1480. you get the dereference and address-of operation as a result of the assignment
  1481. (behind the scenes, this is a result of overloading casting mechanisms). Thus
  1482. the last line of the last example,</p>
  1483. <div class="doc_code">
  1484. <pre>
  1485. Instruction *pinst = &amp;*i;
  1486. </pre>
  1487. </div>
  1488. <p>is semantically equivalent to</p>
  1489. <div class="doc_code">
  1490. <pre>
  1491. Instruction *pinst = i;
  1492. </pre>
  1493. </div>
  1494. <p>It's also possible to turn a class pointer into the corresponding iterator,
  1495. and this is a constant time operation (very efficient). The following code
  1496. snippet illustrates use of the conversion constructors provided by LLVM
  1497. iterators. By using these, you can explicitly grab the iterator of something
  1498. without actually obtaining it via iteration over some structure:</p>
  1499. <div class="doc_code">
  1500. <pre>
  1501. void printNextInstruction(Instruction* inst) {
  1502. BasicBlock::iterator it(inst);
  1503. ++it; // <i>After this line, it refers to the instruction after *inst</i>
  1504. if (it != inst-&gt;getParent()-&gt;end()) errs() &lt;&lt; *it &lt;&lt; "\n";
  1505. }
  1506. </pre>
  1507. </div>
  1508. <p>Unfortunately, these implicit conversions come at a cost; they prevent
  1509. these iterators from conforming to standard iterator conventions, and thus
  1510. from being usable with standard algorithms and containers. For example, they
  1511. prevent the following code, where <tt>B</tt> is a <tt>BasicBlock</tt>,
  1512. from compiling:</p>
  1513. <div class="doc_code">
  1514. <pre>
  1515. llvm::SmallVector&lt;llvm::Instruction *, 16&gt;(B-&gt;begin(), B-&gt;end());
  1516. </pre>
  1517. </div>
  1518. <p>Because of this, these implicit conversions may be removed some day,
  1519. and <tt>operator*</tt> changed to return a pointer instead of a reference.</p>
  1520. </div>
  1521. <!--_______________________________________________________________________-->
  1522. <div class="doc_subsubsection">
  1523. <a name="iterate_complex">Finding call sites: a slightly more complex
  1524. example</a>
  1525. </div>
  1526. <div class="doc_text">
  1527. <p>Say that you're writing a FunctionPass and would like to count all the
  1528. locations in the entire module (that is, across every <tt>Function</tt>) where a
  1529. certain function (i.e., some <tt>Function</tt>*) is already in scope. As you'll
  1530. learn later, you may want to use an <tt>InstVisitor</tt> to accomplish this in a
  1531. much more straight-forward manner, but this example will allow us to explore how
  1532. you'd do it if you didn't have <tt>InstVisitor</tt> around. In pseudo-code, this
  1533. is what we want to do:</p>
  1534. <div class="doc_code">
  1535. <pre>
  1536. initialize callCounter to zero
  1537. for each Function f in the Module
  1538. for each BasicBlock b in f
  1539. for each Instruction i in b
  1540. if (i is a CallInst and calls the given function)
  1541. increment callCounter
  1542. </pre>
  1543. </div>
  1544. <p>And the actual code is (remember, because we're writing a
  1545. <tt>FunctionPass</tt>, our <tt>FunctionPass</tt>-derived class simply has to
  1546. override the <tt>runOnFunction</tt> method):</p>
  1547. <div class="doc_code">
  1548. <pre>
  1549. Function* targetFunc = ...;
  1550. class OurFunctionPass : public FunctionPass {
  1551. public:
  1552. OurFunctionPass(): callCounter(0) { }
  1553. virtual runOnFunction(Function&amp; F) {
  1554. for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
  1555. for (BasicBlock::iterator i = b-&gt;begin(), ie = b-&gt;end(); i != ie; ++i) {
  1556. if (<a href="#CallInst">CallInst</a>* callInst = <a href="#isa">dyn_cast</a>&lt;<a
  1557. href="#CallInst">CallInst</a>&gt;(&amp;*i)) {
  1558. // <i>We know we've encountered a call instruction, so we</i>
  1559. // <i>need to determine if it's a call to the</i>
  1560. // <i>function pointed to by m_func or not.</i>
  1561. if (callInst-&gt;getCalledFunction() == targetFunc)
  1562. ++callCounter;
  1563. }
  1564. }
  1565. }
  1566. }
  1567. private:
  1568. unsigned callCounter;
  1569. };
  1570. </pre>
  1571. </div>
  1572. </div>
  1573. <!--_______________________________________________________________________-->
  1574. <div class="doc_subsubsection">
  1575. <a name="calls_and_invokes">Treating calls and invokes the same way</a>
  1576. </div>
  1577. <div class="doc_text">
  1578. <p>You may have noticed that the previous example was a bit oversimplified in
  1579. that it did not deal with call sites generated by 'invoke' instructions. In
  1580. this, and in other situations, you may find that you want to treat
  1581. <tt>CallInst</tt>s and <tt>InvokeInst</tt>s the same way, even though their
  1582. most-specific common base class is <tt>Instruction</tt>, which includes lots of
  1583. less closely-related things. For these cases, LLVM provides a handy wrapper
  1584. class called <a
  1585. href="http://llvm.org/doxygen/classllvm_1_1CallSite.html"><tt>CallSite</tt></a>.
  1586. It is essentially a wrapper around an <tt>Instruction</tt> pointer, with some
  1587. methods that provide functionality common to <tt>CallInst</tt>s and
  1588. <tt>InvokeInst</tt>s.</p>
  1589. <p>This class has "value semantics": it should be passed by value, not by
  1590. reference and it should not be dynamically allocated or deallocated using
  1591. <tt>operator new</tt> or <tt>operator delete</tt>. It is efficiently copyable,
  1592. assignable and constructable, with costs equivalents to that of a bare pointer.
  1593. If you look at its definition, it has only a single pointer member.</p>
  1594. </div>
  1595. <!--_______________________________________________________________________-->
  1596. <div class="doc_subsubsection">
  1597. <a name="iterate_chains">Iterating over def-use &amp; use-def chains</a>
  1598. </div>
  1599. <div class="doc_text">
  1600. <p>Frequently, we might have an instance of the <a
  1601. href="/doxygen/classllvm_1_1Value.html">Value Class</a> and we want to
  1602. determine which <tt>User</tt>s use the <tt>Value</tt>. The list of all
  1603. <tt>User</tt>s of a particular <tt>Value</tt> is called a <i>def-use</i> chain.
  1604. For example, let's say we have a <tt>Function*</tt> named <tt>F</tt> to a
  1605. particular function <tt>foo</tt>. Finding all of the instructions that
  1606. <i>use</i> <tt>foo</tt> is as simple as iterating over the <i>def-use</i> chain
  1607. of <tt>F</tt>:</p>
  1608. <div class="doc_code">
  1609. <pre>
  1610. Function *F = ...;
  1611. for (Value::use_iterator i = F-&gt;use_begin(), e = F-&gt;use_end(); i != e; ++i)
  1612. if (Instruction *Inst = dyn_cast&lt;Instruction&gt;(*i)) {
  1613. errs() &lt;&lt; "F is used in instruction:\n";
  1614. errs() &lt;&lt; *Inst &lt;&lt; "\n";
  1615. }
  1616. </pre>
  1617. </div>
  1618. <p>Note that dereferencing a <tt>Value::use_iterator</tt> is not a very cheap
  1619. operation. Instead of performing <tt>*i</tt> above several times, consider
  1620. doing it only once in the loop body and reusing its result.</p>
  1621. <p>Alternatively, it's common to have an instance of the <a
  1622. href="/doxygen/classllvm_1_1User.html">User Class</a> and need to know what
  1623. <tt>Value</tt>s are used by it. The list of all <tt>Value</tt>s used by a
  1624. <tt>User</tt> is known as a <i>use-def</i> chain. Instances of class
  1625. <tt>Instruction</tt> are common <tt>User</tt>s, so we might want to iterate over
  1626. all of the values that a particular instruction uses (that is, the operands of
  1627. the particular <tt>Instruction</tt>):</p>
  1628. <div class="doc_code">
  1629. <pre>
  1630. Instruction *pi = ...;
  1631. for (User::op_iterator i = pi-&gt;op_begin(), e = pi-&gt;op_end(); i != e; ++i) {
  1632. Value *v = *i;
  1633. // <i>...</i>
  1634. }
  1635. </pre>
  1636. </div>
  1637. <p>Declaring objects as <tt>const</tt> is an important tool of enforcing
  1638. mutation free algorithms (such as analyses, etc.). For this purpose above
  1639. iterators come in constant flavors as <tt>Value::const_use_iterator</tt>
  1640. and <tt>Value::const_op_iterator</tt>. They automatically arise when
  1641. calling <tt>use/op_begin()</tt> on <tt>const Value*</tt>s or
  1642. <tt>const User*</tt>s respectively. Upon dereferencing, they return
  1643. <tt>const Use*</tt>s. Otherwise the above patterns remain unchanged.</p>
  1644. </div>
  1645. <!--_______________________________________________________________________-->
  1646. <div class="doc_subsubsection">
  1647. <a name="iterate_preds">Iterating over predecessors &amp;
  1648. successors of blocks</a>
  1649. </div>
  1650. <div class="doc_text">
  1651. <p>Iterating over the predecessors and successors of a block is quite easy
  1652. with the routines defined in <tt>"llvm/Support/CFG.h"</tt>. Just use code like
  1653. this to iterate over all predecessors of BB:</p>
  1654. <div class="doc_code">
  1655. <pre>
  1656. #include "llvm/Support/CFG.h"
  1657. BasicBlock *BB = ...;
  1658. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  1659. BasicBlock *Pred = *PI;
  1660. // <i>...</i>
  1661. }
  1662. </pre>
  1663. </div>
  1664. <p>Similarly, to iterate over successors use
  1665. succ_iterator/succ_begin/succ_end.</p>
  1666. </div>
  1667. <!-- ======================================================================= -->
  1668. <div class="doc_subsection">
  1669. <a name="simplechanges">Making simple changes</a>
  1670. </div>
  1671. <div class="doc_text">
  1672. <p>There are some primitive transformation operations present in the LLVM
  1673. infrastructure that are worth knowing about. When performing
  1674. transformations, it's fairly common to manipulate the contents of basic
  1675. blocks. This section describes some of the common methods for doing so
  1676. and gives example code.</p>
  1677. </div>
  1678. <!--_______________________________________________________________________-->
  1679. <div class="doc_subsubsection">
  1680. <a name="schanges_creating">Creating and inserting new
  1681. <tt>Instruction</tt>s</a>
  1682. </div>
  1683. <div class="doc_text">
  1684. <p><i>Instantiating Instructions</i></p>
  1685. <p>Creation of <tt>Instruction</tt>s is straight-forward: simply call the
  1686. constructor for the kind of instruction to instantiate and provide the necessary
  1687. parameters. For example, an <tt>AllocaInst</tt> only <i>requires</i> a
  1688. (const-ptr-to) <tt>Type</tt>. Thus:</p>
  1689. <div class="doc_code">
  1690. <pre>
  1691. AllocaInst* ai = new AllocaInst(Type::Int32Ty);
  1692. </pre>
  1693. </div>
  1694. <p>will create an <tt>AllocaInst</tt> instance that represents the allocation of
  1695. one integer in the current stack frame, at run time. Each <tt>Instruction</tt>
  1696. subclass is likely to have varying default parameters which change the semantics
  1697. of the instruction, so refer to the <a
  1698. href="/doxygen/classllvm_1_1Instruction.html">doxygen documentation for the subclass of
  1699. Instruction</a> that you're interested in instantiating.</p>
  1700. <p><i>Naming values</i></p>
  1701. <p>It is very useful to name the values of instructions when you're able to, as
  1702. this facilitates the debugging of your transformations. If you end up looking
  1703. at generated LLVM machine code, you definitely want to have logical names
  1704. associated with the results of instructions! By supplying a value for the
  1705. <tt>Name</tt> (default) parameter of the <tt>Instruction</tt> constructor, you
  1706. associate a logical name with the result of the instruction's execution at
  1707. run time. For example, say that I'm writing a transformation that dynamically
  1708. allocates space for an integer on the stack, and that integer is going to be
  1709. used as some kind of index by some other code. To accomplish this, I place an
  1710. <tt>AllocaInst</tt> at the first point in the first <tt>BasicBlock</tt> of some
  1711. <tt>Function</tt>, and I'm intending to use it within the same
  1712. <tt>Function</tt>. I might do:</p>
  1713. <div class="doc_code">
  1714. <pre>
  1715. AllocaInst* pa = new AllocaInst(Type::Int32Ty, 0, "indexLoc");
  1716. </pre>
  1717. </div>
  1718. <p>where <tt>indexLoc</tt> is now the logical name of the instruction's
  1719. execution value, which is a pointer to an integer on the run time stack.</p>
  1720. <p><i>Inserting instructions</i></p>
  1721. <p>There are essentially two ways to insert an <tt>Instruction</tt>
  1722. into an existing sequence of instructions that form a <tt>BasicBlock</tt>:</p>
  1723. <ul>
  1724. <li>Insertion into an explicit instruction list
  1725. <p>Given a <tt>BasicBlock* pb</tt>, an <tt>Instruction* pi</tt> within that
  1726. <tt>BasicBlock</tt>, and a newly-created instruction we wish to insert
  1727. before <tt>*pi</tt>, we do the following: </p>
  1728. <div class="doc_code">
  1729. <pre>
  1730. BasicBlock *pb = ...;
  1731. Instruction *pi = ...;
  1732. Instruction *newInst = new Instruction(...);
  1733. pb-&gt;getInstList().insert(pi, newInst); // <i>Inserts newInst before pi in pb</i>
  1734. </pre>
  1735. </div>
  1736. <p>Appending to the end of a <tt>BasicBlock</tt> is so common that
  1737. the <tt>Instruction</tt> class and <tt>Instruction</tt>-derived
  1738. classes provide constructors which take a pointer to a
  1739. <tt>BasicBlock</tt> to be appended to. For example code that
  1740. looked like: </p>
  1741. <div class="doc_code">
  1742. <pre>
  1743. BasicBlock *pb = ...;
  1744. Instruction *newInst = new Instruction(...);
  1745. pb-&gt;getInstList().push_back(newInst); // <i>Appends newInst to pb</i>
  1746. </pre>
  1747. </div>
  1748. <p>becomes: </p>
  1749. <div class="doc_code">
  1750. <pre>
  1751. BasicBlock *pb = ...;
  1752. Instruction *newInst = new Instruction(..., pb);
  1753. </pre>
  1754. </div>
  1755. <p>which is much cleaner, especially if you are creating
  1756. long instruction streams.</p></li>
  1757. <li>Insertion into an implicit instruction list
  1758. <p><tt>Instruction</tt> instances that are already in <tt>BasicBlock</tt>s
  1759. are implicitly associated with an existing instruction list: the instruction
  1760. list of the enclosing basic block. Thus, we could have accomplished the same
  1761. thing as the above code without being given a <tt>BasicBlock</tt> by doing:
  1762. </p>
  1763. <div class="doc_code">
  1764. <pre>
  1765. Instruction *pi = ...;
  1766. Instruction *newInst = new Instruction(...);
  1767. pi-&gt;getParent()-&gt;getInstList().insert(pi, newInst);
  1768. </pre>
  1769. </div>
  1770. <p>In fact, this sequence of steps occurs so frequently that the
  1771. <tt>Instruction</tt> class and <tt>Instruction</tt>-derived classes provide
  1772. constructors which take (as a default parameter) a pointer to an
  1773. <tt>Instruction</tt> which the newly-created <tt>Instruction</tt> should
  1774. precede. That is, <tt>Instruction</tt> constructors are capable of
  1775. inserting the newly-created instance into the <tt>BasicBlock</tt> of a
  1776. provided instruction, immediately before that instruction. Using an
  1777. <tt>Instruction</tt> constructor with a <tt>insertBefore</tt> (default)
  1778. parameter, the above code becomes:</p>
  1779. <div class="doc_code">
  1780. <pre>
  1781. Instruction* pi = ...;
  1782. Instruction* newInst = new Instruction(..., pi);
  1783. </pre>
  1784. </div>
  1785. <p>which is much cleaner, especially if you're creating a lot of
  1786. instructions and adding them to <tt>BasicBlock</tt>s.</p></li>
  1787. </ul>
  1788. </div>
  1789. <!--_______________________________________________________________________-->
  1790. <div class="doc_subsubsection">
  1791. <a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a>
  1792. </div>
  1793. <div class="doc_text">
  1794. <p>Deleting an instruction from an existing sequence of instructions that form a
  1795. <a href="#BasicBlock"><tt>BasicBlock</tt></a> is very straight-forward. First,
  1796. you must have a pointer to the instruction that you wish to delete. Second, you
  1797. need to obtain the pointer to that instruction's basic block. You use the
  1798. pointer to the basic block to get its list of instructions and then use the
  1799. erase function to remove your instruction. For example:</p>
  1800. <div class="doc_code">
  1801. <pre>
  1802. <a href="#Instruction">Instruction</a> *I = .. ;
  1803. I-&gt;eraseFromParent();
  1804. </pre>
  1805. </div>
  1806. </div>
  1807. <!--_______________________________________________________________________-->
  1808. <div class="doc_subsubsection">
  1809. <a name="schanges_replacing">Replacing an <tt>Instruction</tt> with another
  1810. <tt>Value</tt></a>
  1811. </div>
  1812. <div class="doc_text">
  1813. <p><i>Replacing individual instructions</i></p>
  1814. <p>Including "<a href="/doxygen/BasicBlockUtils_8h-source.html">llvm/Transforms/Utils/BasicBlockUtils.h</a>"
  1815. permits use of two very useful replace functions: <tt>ReplaceInstWithValue</tt>
  1816. and <tt>ReplaceInstWithInst</tt>.</p>
  1817. <h4><a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a></h4>
  1818. <ul>
  1819. <li><tt>ReplaceInstWithValue</tt>
  1820. <p>This function replaces all uses of a given instruction with a value,
  1821. and then removes the original instruction. The following example
  1822. illustrates the replacement of the result of a particular
  1823. <tt>AllocaInst</tt> that allocates memory for a single integer with a null
  1824. pointer to an integer.</p>
  1825. <div class="doc_code">
  1826. <pre>
  1827. AllocaInst* instToReplace = ...;
  1828. BasicBlock::iterator ii(instToReplace);
  1829. ReplaceInstWithValue(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
  1830. Constant::getNullValue(PointerType::getUnqual(Type::Int32Ty)));
  1831. </pre></div></li>
  1832. <li><tt>ReplaceInstWithInst</tt>
  1833. <p>This function replaces a particular instruction with another
  1834. instruction, inserting the new instruction into the basic block at the
  1835. location where the old instruction was, and replacing any uses of the old
  1836. instruction with the new instruction. The following example illustrates
  1837. the replacement of one <tt>AllocaInst</tt> with another.</p>
  1838. <div class="doc_code">
  1839. <pre>
  1840. AllocaInst* instToReplace = ...;
  1841. BasicBlock::iterator ii(instToReplace);
  1842. ReplaceInstWithInst(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
  1843. new AllocaInst(Type::Int32Ty, 0, "ptrToReplacedInt"));
  1844. </pre></div></li>
  1845. </ul>
  1846. <p><i>Replacing multiple uses of <tt>User</tt>s and <tt>Value</tt>s</i></p>
  1847. <p>You can use <tt>Value::replaceAllUsesWith</tt> and
  1848. <tt>User::replaceUsesOfWith</tt> to change more than one use at a time. See the
  1849. doxygen documentation for the <a href="/doxygen/classllvm_1_1Value.html">Value Class</a>
  1850. and <a href="/doxygen/classllvm_1_1User.html">User Class</a>, respectively, for more
  1851. information.</p>
  1852. <!-- Value::replaceAllUsesWith User::replaceUsesOfWith Point out:
  1853. include/llvm/Transforms/Utils/ especially BasicBlockUtils.h with:
  1854. ReplaceInstWithValue, ReplaceInstWithInst -->
  1855. </div>
  1856. <!--_______________________________________________________________________-->
  1857. <div class="doc_subsubsection">
  1858. <a name="schanges_deletingGV">Deleting <tt>GlobalVariable</tt>s</a>
  1859. </div>
  1860. <div class="doc_text">
  1861. <p>Deleting a global variable from a module is just as easy as deleting an
  1862. Instruction. First, you must have a pointer to the global variable that you wish
  1863. to delete. You use this pointer to erase it from its parent, the module.
  1864. For example:</p>
  1865. <div class="doc_code">
  1866. <pre>
  1867. <a href="#GlobalVariable">GlobalVariable</a> *GV = .. ;
  1868. GV-&gt;eraseFromParent();
  1869. </pre>
  1870. </div>
  1871. </div>
  1872. <!-- ======================================================================= -->
  1873. <div class="doc_subsection">
  1874. <a name="create_types">How to Create Types</a>
  1875. </div>
  1876. <div class="doc_text">
  1877. <p>In generating IR, you may need some complex types. If you know these types
  1878. statically, you can use <tt>TypeBuilder&lt;...&gt;::get()</tt>, defined
  1879. in <tt>llvm/Support/TypeBuilder.h</tt>, to retrieve them. <tt>TypeBuilder</tt>
  1880. has two forms depending on whether you're building types for cross-compilation
  1881. or native library use. <tt>TypeBuilder&lt;T, true&gt;</tt> requires
  1882. that <tt>T</tt> be independent of the host environment, meaning that it's built
  1883. out of types from
  1884. the <a href="/doxygen/namespacellvm_1_1types.html"><tt>llvm::types</tt></a>
  1885. namespace and pointers, functions, arrays, etc. built of
  1886. those. <tt>TypeBuilder&lt;T, false&gt;</tt> additionally allows native C types
  1887. whose size may depend on the host compiler. For example,</p>
  1888. <div class="doc_code">
  1889. <pre>
  1890. FunctionType *ft = TypeBuilder&lt;types::i&lt;8&gt;(types::i&lt;32&gt;*), true&gt;::get();
  1891. </pre>
  1892. </div>
  1893. <p>is easier to read and write than the equivalent</p>
  1894. <div class="doc_code">
  1895. <pre>
  1896. std::vector&lt;const Type*&gt; params;
  1897. params.push_back(PointerType::getUnqual(Type::Int32Ty));
  1898. FunctionType *ft = FunctionType::get(Type::Int8Ty, params, false);
  1899. </pre>
  1900. </div>
  1901. <p>See the <a href="/doxygen/TypeBuilder_8h-source.html#l00001">class
  1902. comment</a> for more details.</p>
  1903. </div>
  1904. <!-- *********************************************************************** -->
  1905. <div class="doc_section">
  1906. <a name="threading">Threads and LLVM</a>
  1907. </div>
  1908. <!-- *********************************************************************** -->
  1909. <div class="doc_text">
  1910. <p>
  1911. This section describes the interaction of the LLVM APIs with multithreading,
  1912. both on the part of client applications, and in the JIT, in the hosted
  1913. application.
  1914. </p>
  1915. <p>
  1916. Note that LLVM's support for multithreading is still relatively young. Up
  1917. through version 2.5, the execution of threaded hosted applications was
  1918. supported, but not threaded client access to the APIs. While this use case is
  1919. now supported, clients <em>must</em> adhere to the guidelines specified below to
  1920. ensure proper operation in multithreaded mode.
  1921. </p>
  1922. <p>
  1923. Note that, on Unix-like platforms, LLVM requires the presence of GCC's atomic
  1924. intrinsics in order to support threaded operation. If you need a
  1925. multhreading-capable LLVM on a platform without a suitably modern system
  1926. compiler, consider compiling LLVM and LLVM-GCC in single-threaded mode, and
  1927. using the resultant compiler to build a copy of LLVM with multithreading
  1928. support.
  1929. </p>
  1930. </div>
  1931. <!-- ======================================================================= -->
  1932. <div class="doc_subsection">
  1933. <a name="startmultithreaded">Entering and Exiting Multithreaded Mode</a>
  1934. </div>
  1935. <div class="doc_text">
  1936. <p>
  1937. In order to properly protect its internal data structures while avoiding
  1938. excessive locking overhead in the single-threaded case, the LLVM must intialize
  1939. certain data structures necessary to provide guards around its internals. To do
  1940. so, the client program must invoke <tt>llvm_start_multithreaded()</tt> before
  1941. making any concurrent LLVM API calls. To subsequently tear down these
  1942. structures, use the <tt>llvm_stop_multithreaded()</tt> call. You can also use
  1943. the <tt>llvm_is_multithreaded()</tt> call to check the status of multithreaded
  1944. mode.
  1945. </p>
  1946. <p>
  1947. Note that both of these calls must be made <em>in isolation</em>. That is to
  1948. say that no other LLVM API calls may be executing at any time during the
  1949. execution of <tt>llvm_start_multithreaded()</tt> or <tt>llvm_stop_multithreaded
  1950. </tt>. It's is the client's responsibility to enforce this isolation.
  1951. </p>
  1952. <p>
  1953. The return value of <tt>llvm_start_multithreaded()</tt> indicates the success or
  1954. failure of the initialization. Failure typically indicates that your copy of
  1955. LLVM was built without multithreading support, typically because GCC atomic
  1956. intrinsics were not found in your system compiler. In this case, the LLVM API
  1957. will not be safe for concurrent calls. However, it <em>will</em> be safe for
  1958. hosting threaded applications in the JIT, though <a href="#jitthreading">care
  1959. must be taken</a> to ensure that side exits and the like do not accidentally
  1960. result in concurrent LLVM API calls.
  1961. </p>
  1962. </div>
  1963. <!-- ======================================================================= -->
  1964. <div class="doc_subsection">
  1965. <a name="shutdown">Ending Execution with <tt>llvm_shutdown()</tt></a>
  1966. </div>
  1967. <div class="doc_text">
  1968. <p>
  1969. When you are done using the LLVM APIs, you should call <tt>llvm_shutdown()</tt>
  1970. to deallocate memory used for internal structures. This will also invoke
  1971. <tt>llvm_stop_multithreaded()</tt> if LLVM is operating in multithreaded mode.
  1972. As such, <tt>llvm_shutdown()</tt> requires the same isolation guarantees as
  1973. <tt>llvm_stop_multithreaded()</tt>.
  1974. </p>
  1975. <p>
  1976. Note that, if you use scope-based shutdown, you can use the
  1977. <tt>llvm_shutdown_obj</tt> class, which calls <tt>llvm_shutdown()</tt> in its
  1978. destructor.
  1979. </div>
  1980. <!-- ======================================================================= -->
  1981. <div class="doc_subsection">
  1982. <a name="managedstatic">Lazy Initialization with <tt>ManagedStatic</tt></a>
  1983. </div>
  1984. <div class="doc_text">
  1985. <p>
  1986. <tt>ManagedStatic</tt> is a utility class in LLVM used to implement static
  1987. initialization of static resources, such as the global type tables. Before the
  1988. invocation of <tt>llvm_shutdown()</tt>, it implements a simple lazy
  1989. initialization scheme. Once <tt>llvm_start_multithreaded()</tt> returns,
  1990. however, it uses double-checked locking to implement thread-safe lazy
  1991. initialization.
  1992. </p>
  1993. <p>
  1994. Note that, because no other threads are allowed to issue LLVM API calls before
  1995. <tt>llvm_start_multithreaded()</tt> returns, it is possible to have
  1996. <tt>ManagedStatic</tt>s of <tt>llvm::sys::Mutex</tt>s.
  1997. </p>
  1998. <p>
  1999. The <tt>llvm_acquire_global_lock()</tt> and <tt>llvm_release_global_lock</tt>
  2000. APIs provide access to the global lock used to implement the double-checked
  2001. locking for lazy initialization. These should only be used internally to LLVM,
  2002. and only if you know what you're doing!
  2003. </p>
  2004. </div>
  2005. <!-- ======================================================================= -->
  2006. <div class="doc_subsection">
  2007. <a name="llvmcontext">Achieving Isolation with <tt>LLVMContext</tt></a>
  2008. </div>
  2009. <div class="doc_text">
  2010. <p>
  2011. <tt>LLVMContext</tt> is an opaque class in the LLVM API which clients can use
  2012. to operate multiple, isolated instances of LLVM concurrently within the same
  2013. address space. For instance, in a hypothetical compile-server, the compilation
  2014. of an individual translation unit is conceptually independent from all the
  2015. others, and it would be desirable to be able to compile incoming translation
  2016. units concurrently on independent server threads. Fortunately,
  2017. <tt>LLVMContext</tt> exists to enable just this kind of scenario!
  2018. </p>
  2019. <p>
  2020. Conceptually, <tt>LLVMContext</tt> provides isolation. Every LLVM entity
  2021. (<tt>Module</tt>s, <tt>Value</tt>s, <tt>Type</tt>s, <tt>Constant</tt>s, etc.)
  2022. in LLVM's in-memory IR belongs to an <tt>LLVMContext</tt>. Entities in
  2023. different contexts <em>cannot</em> interact with each other: <tt>Module</tt>s in
  2024. different contexts cannot be linked together, <tt>Function</tt>s cannot be added
  2025. to <tt>Module</tt>s in different contexts, etc. What this means is that is is
  2026. safe to compile on multiple threads simultaneously, as long as no two threads
  2027. operate on entities within the same context.
  2028. </p>
  2029. <p>
  2030. In practice, very few places in the API require the explicit specification of a
  2031. <tt>LLVMContext</tt>, other than the <tt>Type</tt> creation/lookup APIs.
  2032. Because every <tt>Type</tt> carries a reference to its owning context, most
  2033. other entities can determine what context they belong to by looking at their
  2034. own <tt>Type</tt>. If you are adding new entities to LLVM IR, please try to
  2035. maintain this interface design.
  2036. </p>
  2037. <p>
  2038. For clients that do <em>not</em> require the benefits of isolation, LLVM
  2039. provides a convenience API <tt>getGlobalContext()</tt>. This returns a global,
  2040. lazily initialized <tt>LLVMContext</tt> that may be used in situations where
  2041. isolation is not a concern.
  2042. </p>
  2043. </div>
  2044. <!-- ======================================================================= -->
  2045. <div class="doc_subsection">
  2046. <a name="jitthreading">Threads and the JIT</a>
  2047. </div>
  2048. <div class="doc_text">
  2049. <p>
  2050. LLVM's "eager" JIT compiler is safe to use in threaded programs. Multiple
  2051. threads can call <tt>ExecutionEngine::getPointerToFunction()</tt> or
  2052. <tt>ExecutionEngine::runFunction()</tt> concurrently, and multiple threads can
  2053. run code output by the JIT concurrently. The user must still ensure that only
  2054. one thread accesses IR in a given <tt>LLVMContext</tt> while another thread
  2055. might be modifying it. One way to do that is to always hold the JIT lock while
  2056. accessing IR outside the JIT (the JIT <em>modifies</em> the IR by adding
  2057. <tt>CallbackVH</tt>s). Another way is to only
  2058. call <tt>getPointerToFunction()</tt> from the <tt>LLVMContext</tt>'s thread.
  2059. </p>
  2060. <p>When the JIT is configured to compile lazily (using
  2061. <tt>ExecutionEngine::DisableLazyCompilation(false)</tt>), there is currently a
  2062. <a href="http://llvm.org/bugs/show_bug.cgi?id=5184">race condition</a> in
  2063. updating call sites after a function is lazily-jitted. It's still possible to
  2064. use the lazy JIT in a threaded program if you ensure that only one thread at a
  2065. time can call any particular lazy stub and that the JIT lock guards any IR
  2066. access, but we suggest using only the eager JIT in threaded programs.
  2067. </p>
  2068. </div>
  2069. <!-- *********************************************************************** -->
  2070. <div class="doc_section">
  2071. <a name="advanced">Advanced Topics</a>
  2072. </div>
  2073. <!-- *********************************************************************** -->
  2074. <div class="doc_text">
  2075. <p>
  2076. This section describes some of the advanced or obscure API's that most clients
  2077. do not need to be aware of. These API's tend manage the inner workings of the
  2078. LLVM system, and only need to be accessed in unusual circumstances.
  2079. </p>
  2080. </div>
  2081. <!-- ======================================================================= -->
  2082. <div class="doc_subsection">
  2083. <a name="TypeResolve">LLVM Type Resolution</a>
  2084. </div>
  2085. <div class="doc_text">
  2086. <p>
  2087. The LLVM type system has a very simple goal: allow clients to compare types for
  2088. structural equality with a simple pointer comparison (aka a shallow compare).
  2089. This goal makes clients much simpler and faster, and is used throughout the LLVM
  2090. system.
  2091. </p>
  2092. <p>
  2093. Unfortunately achieving this goal is not a simple matter. In particular,
  2094. recursive types and late resolution of opaque types makes the situation very
  2095. difficult to handle. Fortunately, for the most part, our implementation makes
  2096. most clients able to be completely unaware of the nasty internal details. The
  2097. primary case where clients are exposed to the inner workings of it are when
  2098. building a recursive type. In addition to this case, the LLVM bitcode reader,
  2099. assembly parser, and linker also have to be aware of the inner workings of this
  2100. system.
  2101. </p>
  2102. <p>
  2103. For our purposes below, we need three concepts. First, an "Opaque Type" is
  2104. exactly as defined in the <a href="LangRef.html#t_opaque">language
  2105. reference</a>. Second an "Abstract Type" is any type which includes an
  2106. opaque type as part of its type graph (for example "<tt>{ opaque, i32 }</tt>").
  2107. Third, a concrete type is a type that is not an abstract type (e.g. "<tt>{ i32,
  2108. float }</tt>").
  2109. </p>
  2110. </div>
  2111. <!-- ______________________________________________________________________ -->
  2112. <div class="doc_subsubsection">
  2113. <a name="BuildRecType">Basic Recursive Type Construction</a>
  2114. </div>
  2115. <div class="doc_text">
  2116. <p>
  2117. Because the most common question is "how do I build a recursive type with LLVM",
  2118. we answer it now and explain it as we go. Here we include enough to cause this
  2119. to be emitted to an output .ll file:
  2120. </p>
  2121. <div class="doc_code">
  2122. <pre>
  2123. %mylist = type { %mylist*, i32 }
  2124. </pre>
  2125. </div>
  2126. <p>
  2127. To build this, use the following LLVM APIs:
  2128. </p>
  2129. <div class="doc_code">
  2130. <pre>
  2131. // <i>Create the initial outer struct</i>
  2132. <a href="#PATypeHolder">PATypeHolder</a> StructTy = OpaqueType::get();
  2133. std::vector&lt;const Type*&gt; Elts;
  2134. Elts.push_back(PointerType::getUnqual(StructTy));
  2135. Elts.push_back(Type::Int32Ty);
  2136. StructType *NewSTy = StructType::get(Elts);
  2137. // <i>At this point, NewSTy = "{ opaque*, i32 }". Tell VMCore that</i>
  2138. // <i>the struct and the opaque type are actually the same.</i>
  2139. cast&lt;OpaqueType&gt;(StructTy.get())-&gt;<a href="#refineAbstractTypeTo">refineAbstractTypeTo</a>(NewSTy);
  2140. // <i>NewSTy is potentially invalidated, but StructTy (a <a href="#PATypeHolder">PATypeHolder</a>) is</i>
  2141. // <i>kept up-to-date</i>
  2142. NewSTy = cast&lt;StructType&gt;(StructTy.get());
  2143. // <i>Add a name for the type to the module symbol table (optional)</i>
  2144. MyModule-&gt;addTypeName("mylist", NewSTy);
  2145. </pre>
  2146. </div>
  2147. <p>
  2148. This code shows the basic approach used to build recursive types: build a
  2149. non-recursive type using 'opaque', then use type unification to close the cycle.
  2150. The type unification step is performed by the <tt><a
  2151. href="#refineAbstractTypeTo">refineAbstractTypeTo</a></tt> method, which is
  2152. described next. After that, we describe the <a
  2153. href="#PATypeHolder">PATypeHolder class</a>.
  2154. </p>
  2155. </div>
  2156. <!-- ______________________________________________________________________ -->
  2157. <div class="doc_subsubsection">
  2158. <a name="refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a>
  2159. </div>
  2160. <div class="doc_text">
  2161. <p>
  2162. The <tt>refineAbstractTypeTo</tt> method starts the type unification process.
  2163. While this method is actually a member of the DerivedType class, it is most
  2164. often used on OpaqueType instances. Type unification is actually a recursive
  2165. process. After unification, types can become structurally isomorphic to
  2166. existing types, and all duplicates are deleted (to preserve pointer equality).
  2167. </p>
  2168. <p>
  2169. In the example above, the OpaqueType object is definitely deleted.
  2170. Additionally, if there is an "{ \2*, i32}" type already created in the system,
  2171. the pointer and struct type created are <b>also</b> deleted. Obviously whenever
  2172. a type is deleted, any "Type*" pointers in the program are invalidated. As
  2173. such, it is safest to avoid having <i>any</i> "Type*" pointers to abstract types
  2174. live across a call to <tt>refineAbstractTypeTo</tt> (note that non-abstract
  2175. types can never move or be deleted). To deal with this, the <a
  2176. href="#PATypeHolder">PATypeHolder</a> class is used to maintain a stable
  2177. reference to a possibly refined type, and the <a
  2178. href="#AbstractTypeUser">AbstractTypeUser</a> class is used to update more
  2179. complex datastructures.
  2180. </p>
  2181. </div>
  2182. <!-- ______________________________________________________________________ -->
  2183. <div class="doc_subsubsection">
  2184. <a name="PATypeHolder">The PATypeHolder Class</a>
  2185. </div>
  2186. <div class="doc_text">
  2187. <p>
  2188. PATypeHolder is a form of a "smart pointer" for Type objects. When VMCore
  2189. happily goes about nuking types that become isomorphic to existing types, it
  2190. automatically updates all PATypeHolder objects to point to the new type. In the
  2191. example above, this allows the code to maintain a pointer to the resultant
  2192. resolved recursive type, even though the Type*'s are potentially invalidated.
  2193. </p>
  2194. <p>
  2195. PATypeHolder is an extremely light-weight object that uses a lazy union-find
  2196. implementation to update pointers. For example the pointer from a Value to its
  2197. Type is maintained by PATypeHolder objects.
  2198. </p>
  2199. </div>
  2200. <!-- ______________________________________________________________________ -->
  2201. <div class="doc_subsubsection">
  2202. <a name="AbstractTypeUser">The AbstractTypeUser Class</a>
  2203. </div>
  2204. <div class="doc_text">
  2205. <p>
  2206. Some data structures need more to perform more complex updates when types get
  2207. resolved. To support this, a class can derive from the AbstractTypeUser class.
  2208. This class
  2209. allows it to get callbacks when certain types are resolved. To register to get
  2210. callbacks for a particular type, the DerivedType::{add/remove}AbstractTypeUser
  2211. methods can be called on a type. Note that these methods only work for <i>
  2212. abstract</i> types. Concrete types (those that do not include any opaque
  2213. objects) can never be refined.
  2214. </p>
  2215. </div>
  2216. <!-- ======================================================================= -->
  2217. <div class="doc_subsection">
  2218. <a name="SymbolTable">The <tt>ValueSymbolTable</tt> and
  2219. <tt>TypeSymbolTable</tt> classes</a>
  2220. </div>
  2221. <div class="doc_text">
  2222. <p>The <tt><a href="http://llvm.org/doxygen/classllvm_1_1ValueSymbolTable.html">
  2223. ValueSymbolTable</a></tt> class provides a symbol table that the <a
  2224. href="#Function"><tt>Function</tt></a> and <a href="#Module">
  2225. <tt>Module</tt></a> classes use for naming value definitions. The symbol table
  2226. can provide a name for any <a href="#Value"><tt>Value</tt></a>.
  2227. The <tt><a href="http://llvm.org/doxygen/classllvm_1_1TypeSymbolTable.html">
  2228. TypeSymbolTable</a></tt> class is used by the <tt>Module</tt> class to store
  2229. names for types.</p>
  2230. <p>Note that the <tt>SymbolTable</tt> class should not be directly accessed
  2231. by most clients. It should only be used when iteration over the symbol table
  2232. names themselves are required, which is very special purpose. Note that not
  2233. all LLVM
  2234. <tt><a href="#Value">Value</a></tt>s have names, and those without names (i.e. they have
  2235. an empty name) do not exist in the symbol table.
  2236. </p>
  2237. <p>These symbol tables support iteration over the values/types in the symbol
  2238. table with <tt>begin/end/iterator</tt> and supports querying to see if a
  2239. specific name is in the symbol table (with <tt>lookup</tt>). The
  2240. <tt>ValueSymbolTable</tt> class exposes no public mutator methods, instead,
  2241. simply call <tt>setName</tt> on a value, which will autoinsert it into the
  2242. appropriate symbol table. For types, use the Module::addTypeName method to
  2243. insert entries into the symbol table.</p>
  2244. </div>
  2245. <!-- ======================================================================= -->
  2246. <div class="doc_subsection">
  2247. <a name="UserLayout">The <tt>User</tt> and owned <tt>Use</tt> classes' memory layout</a>
  2248. </div>
  2249. <div class="doc_text">
  2250. <p>The <tt><a href="http://llvm.org/doxygen/classllvm_1_1User.html">
  2251. User</a></tt> class provides a basis for expressing the ownership of <tt>User</tt>
  2252. towards other <tt><a href="http://llvm.org/doxygen/classllvm_1_1Value.html">
  2253. Value</a></tt>s. The <tt><a href="http://llvm.org/doxygen/classllvm_1_1Use.html">
  2254. Use</a></tt> helper class is employed to do the bookkeeping and to facilitate <i>O(1)</i>
  2255. addition and removal.</p>
  2256. <!-- ______________________________________________________________________ -->
  2257. <div class="doc_subsubsection">
  2258. <a name="Use2User">Interaction and relationship between <tt>User</tt> and <tt>Use</tt> objects</a>
  2259. </div>
  2260. <div class="doc_text">
  2261. <p>
  2262. A subclass of <tt>User</tt> can choose between incorporating its <tt>Use</tt> objects
  2263. or refer to them out-of-line by means of a pointer. A mixed variant
  2264. (some <tt>Use</tt>s inline others hung off) is impractical and breaks the invariant
  2265. that the <tt>Use</tt> objects belonging to the same <tt>User</tt> form a contiguous array.
  2266. </p>
  2267. </div>
  2268. <p>
  2269. We have 2 different layouts in the <tt>User</tt> (sub)classes:
  2270. <ul>
  2271. <li><p>Layout a)
  2272. The <tt>Use</tt> object(s) are inside (resp. at fixed offset) of the <tt>User</tt>
  2273. object and there are a fixed number of them.</p>
  2274. <li><p>Layout b)
  2275. The <tt>Use</tt> object(s) are referenced by a pointer to an
  2276. array from the <tt>User</tt> object and there may be a variable
  2277. number of them.</p>
  2278. </ul>
  2279. <p>
  2280. As of v2.4 each layout still possesses a direct pointer to the
  2281. start of the array of <tt>Use</tt>s. Though not mandatory for layout a),
  2282. we stick to this redundancy for the sake of simplicity.
  2283. The <tt>User</tt> object also stores the number of <tt>Use</tt> objects it
  2284. has. (Theoretically this information can also be calculated
  2285. given the scheme presented below.)</p>
  2286. <p>
  2287. Special forms of allocation operators (<tt>operator new</tt>)
  2288. enforce the following memory layouts:</p>
  2289. <ul>
  2290. <li><p>Layout a) is modelled by prepending the <tt>User</tt> object by the <tt>Use[]</tt> array.</p>
  2291. <pre>
  2292. ...---.---.---.---.-------...
  2293. | P | P | P | P | User
  2294. '''---'---'---'---'-------'''
  2295. </pre>
  2296. <li><p>Layout b) is modelled by pointing at the <tt>Use[]</tt> array.</p>
  2297. <pre>
  2298. .-------...
  2299. | User
  2300. '-------'''
  2301. |
  2302. v
  2303. .---.---.---.---...
  2304. | P | P | P | P |
  2305. '---'---'---'---'''
  2306. </pre>
  2307. </ul>
  2308. <i>(In the above figures '<tt>P</tt>' stands for the <tt>Use**</tt> that
  2309. is stored in each <tt>Use</tt> object in the member <tt>Use::Prev</tt>)</i>
  2310. <!-- ______________________________________________________________________ -->
  2311. <div class="doc_subsubsection">
  2312. <a name="Waymarking">The waymarking algorithm</a>
  2313. </div>
  2314. <div class="doc_text">
  2315. <p>
  2316. Since the <tt>Use</tt> objects are deprived of the direct (back)pointer to
  2317. their <tt>User</tt> objects, there must be a fast and exact method to
  2318. recover it. This is accomplished by the following scheme:</p>
  2319. </div>
  2320. A bit-encoding in the 2 LSBits (least significant bits) of the <tt>Use::Prev</tt> allows to find the
  2321. start of the <tt>User</tt> object:
  2322. <ul>
  2323. <li><tt>00</tt> &mdash;&gt; binary digit 0</li>
  2324. <li><tt>01</tt> &mdash;&gt; binary digit 1</li>
  2325. <li><tt>10</tt> &mdash;&gt; stop and calculate (<tt>s</tt>)</li>
  2326. <li><tt>11</tt> &mdash;&gt; full stop (<tt>S</tt>)</li>
  2327. </ul>
  2328. <p>
  2329. Given a <tt>Use*</tt>, all we have to do is to walk till we get
  2330. a stop and we either have a <tt>User</tt> immediately behind or
  2331. we have to walk to the next stop picking up digits
  2332. and calculating the offset:</p>
  2333. <pre>
  2334. .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.----------------
  2335. | 1 | s | 1 | 0 | 1 | 0 | s | 1 | 1 | 0 | s | 1 | 1 | s | 1 | S | User (or User*)
  2336. '---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'----------------
  2337. |+15 |+10 |+6 |+3 |+1
  2338. | | | | |__>
  2339. | | | |__________>
  2340. | | |______________________>
  2341. | |______________________________________>
  2342. |__________________________________________________________>
  2343. </pre>
  2344. <p>
  2345. Only the significant number of bits need to be stored between the
  2346. stops, so that the <i>worst case is 20 memory accesses</i> when there are
  2347. 1000 <tt>Use</tt> objects associated with a <tt>User</tt>.</p>
  2348. <!-- ______________________________________________________________________ -->
  2349. <div class="doc_subsubsection">
  2350. <a name="ReferenceImpl">Reference implementation</a>
  2351. </div>
  2352. <div class="doc_text">
  2353. <p>
  2354. The following literate Haskell fragment demonstrates the concept:</p>
  2355. </div>
  2356. <div class="doc_code">
  2357. <pre>
  2358. > import Test.QuickCheck
  2359. >
  2360. > digits :: Int -> [Char] -> [Char]
  2361. > digits 0 acc = '0' : acc
  2362. > digits 1 acc = '1' : acc
  2363. > digits n acc = digits (n `div` 2) $ digits (n `mod` 2) acc
  2364. >
  2365. > dist :: Int -> [Char] -> [Char]
  2366. > dist 0 [] = ['S']
  2367. > dist 0 acc = acc
  2368. > dist 1 acc = let r = dist 0 acc in 's' : digits (length r) r
  2369. > dist n acc = dist (n - 1) $ dist 1 acc
  2370. >
  2371. > takeLast n ss = reverse $ take n $ reverse ss
  2372. >
  2373. > test = takeLast 40 $ dist 20 []
  2374. >
  2375. </pre>
  2376. </div>
  2377. <p>
  2378. Printing &lt;test&gt; gives: <tt>"1s100000s11010s10100s1111s1010s110s11s1S"</tt></p>
  2379. <p>
  2380. The reverse algorithm computes the length of the string just by examining
  2381. a certain prefix:</p>
  2382. <div class="doc_code">
  2383. <pre>
  2384. > pref :: [Char] -> Int
  2385. > pref "S" = 1
  2386. > pref ('s':'1':rest) = decode 2 1 rest
  2387. > pref (_:rest) = 1 + pref rest
  2388. >
  2389. > decode walk acc ('0':rest) = decode (walk + 1) (acc * 2) rest
  2390. > decode walk acc ('1':rest) = decode (walk + 1) (acc * 2 + 1) rest
  2391. > decode walk acc _ = walk + acc
  2392. >
  2393. </pre>
  2394. </div>
  2395. <p>
  2396. Now, as expected, printing &lt;pref test&gt; gives <tt>40</tt>.</p>
  2397. <p>
  2398. We can <i>quickCheck</i> this with following property:</p>
  2399. <div class="doc_code">
  2400. <pre>
  2401. > testcase = dist 2000 []
  2402. > testcaseLength = length testcase
  2403. >
  2404. > identityProp n = n > 0 && n <= testcaseLength ==> length arr == pref arr
  2405. > where arr = takeLast n testcase
  2406. >
  2407. </pre>
  2408. </div>
  2409. <p>
  2410. As expected &lt;quickCheck identityProp&gt; gives:</p>
  2411. <pre>
  2412. *Main> quickCheck identityProp
  2413. OK, passed 100 tests.
  2414. </pre>
  2415. <p>
  2416. Let's be a bit more exhaustive:</p>
  2417. <div class="doc_code">
  2418. <pre>
  2419. >
  2420. > deepCheck p = check (defaultConfig { configMaxTest = 500 }) p
  2421. >
  2422. </pre>
  2423. </div>
  2424. <p>
  2425. And here is the result of &lt;deepCheck identityProp&gt;:</p>
  2426. <pre>
  2427. *Main> deepCheck identityProp
  2428. OK, passed 500 tests.
  2429. </pre>
  2430. <!-- ______________________________________________________________________ -->
  2431. <div class="doc_subsubsection">
  2432. <a name="Tagging">Tagging considerations</a>
  2433. </div>
  2434. <p>
  2435. To maintain the invariant that the 2 LSBits of each <tt>Use**</tt> in <tt>Use</tt>
  2436. never change after being set up, setters of <tt>Use::Prev</tt> must re-tag the
  2437. new <tt>Use**</tt> on every modification. Accordingly getters must strip the
  2438. tag bits.</p>
  2439. <p>
  2440. For layout b) instead of the <tt>User</tt> we find a pointer (<tt>User*</tt> with LSBit set).
  2441. Following this pointer brings us to the <tt>User</tt>. A portable trick ensures
  2442. that the first bytes of <tt>User</tt> (if interpreted as a pointer) never has
  2443. the LSBit set. (Portability is relying on the fact that all known compilers place the
  2444. <tt>vptr</tt> in the first word of the instances.)</p>
  2445. </div>
  2446. <!-- *********************************************************************** -->
  2447. <div class="doc_section">
  2448. <a name="coreclasses">The Core LLVM Class Hierarchy Reference </a>
  2449. </div>
  2450. <!-- *********************************************************************** -->
  2451. <div class="doc_text">
  2452. <p><tt>#include "<a href="/doxygen/Type_8h-source.html">llvm/Type.h</a>"</tt>
  2453. <br>doxygen info: <a href="/doxygen/classllvm_1_1Type.html">Type Class</a></p>
  2454. <p>The Core LLVM classes are the primary means of representing the program
  2455. being inspected or transformed. The core LLVM classes are defined in
  2456. header files in the <tt>include/llvm/</tt> directory, and implemented in
  2457. the <tt>lib/VMCore</tt> directory.</p>
  2458. </div>
  2459. <!-- ======================================================================= -->
  2460. <div class="doc_subsection">
  2461. <a name="Type">The <tt>Type</tt> class and Derived Types</a>
  2462. </div>
  2463. <div class="doc_text">
  2464. <p><tt>Type</tt> is a superclass of all type classes. Every <tt>Value</tt> has
  2465. a <tt>Type</tt>. <tt>Type</tt> cannot be instantiated directly but only
  2466. through its subclasses. Certain primitive types (<tt>VoidType</tt>,
  2467. <tt>LabelType</tt>, <tt>FloatType</tt> and <tt>DoubleType</tt>) have hidden
  2468. subclasses. They are hidden because they offer no useful functionality beyond
  2469. what the <tt>Type</tt> class offers except to distinguish themselves from
  2470. other subclasses of <tt>Type</tt>.</p>
  2471. <p>All other types are subclasses of <tt>DerivedType</tt>. Types can be
  2472. named, but this is not a requirement. There exists exactly
  2473. one instance of a given shape at any one time. This allows type equality to
  2474. be performed with address equality of the Type Instance. That is, given two
  2475. <tt>Type*</tt> values, the types are identical if the pointers are identical.
  2476. </p>
  2477. </div>
  2478. <!-- _______________________________________________________________________ -->
  2479. <div class="doc_subsubsection">
  2480. <a name="m_Type">Important Public Methods</a>
  2481. </div>
  2482. <div class="doc_text">
  2483. <ul>
  2484. <li><tt>bool isIntegerTy() const</tt>: Returns true for any integer type.</li>
  2485. <li><tt>bool isFloatingPointTy()</tt>: Return true if this is one of the five
  2486. floating point types.</li>
  2487. <li><tt>bool isAbstract()</tt>: Return true if the type is abstract (contains
  2488. an OpaqueType anywhere in its definition).</li>
  2489. <li><tt>bool isSized()</tt>: Return true if the type has known size. Things
  2490. that don't have a size are abstract types, labels and void.</li>
  2491. </ul>
  2492. </div>
  2493. <!-- _______________________________________________________________________ -->
  2494. <div class="doc_subsubsection">
  2495. <a name="derivedtypes">Important Derived Types</a>
  2496. </div>
  2497. <div class="doc_text">
  2498. <dl>
  2499. <dt><tt>IntegerType</tt></dt>
  2500. <dd>Subclass of DerivedType that represents integer types of any bit width.
  2501. Any bit width between <tt>IntegerType::MIN_INT_BITS</tt> (1) and
  2502. <tt>IntegerType::MAX_INT_BITS</tt> (~8 million) can be represented.
  2503. <ul>
  2504. <li><tt>static const IntegerType* get(unsigned NumBits)</tt>: get an integer
  2505. type of a specific bit width.</li>
  2506. <li><tt>unsigned getBitWidth() const</tt>: Get the bit width of an integer
  2507. type.</li>
  2508. </ul>
  2509. </dd>
  2510. <dt><tt>SequentialType</tt></dt>
  2511. <dd>This is subclassed by ArrayType and PointerType
  2512. <ul>
  2513. <li><tt>const Type * getElementType() const</tt>: Returns the type of each
  2514. of the elements in the sequential type. </li>
  2515. </ul>
  2516. </dd>
  2517. <dt><tt>ArrayType</tt></dt>
  2518. <dd>This is a subclass of SequentialType and defines the interface for array
  2519. types.
  2520. <ul>
  2521. <li><tt>unsigned getNumElements() const</tt>: Returns the number of
  2522. elements in the array. </li>
  2523. </ul>
  2524. </dd>
  2525. <dt><tt>PointerType</tt></dt>
  2526. <dd>Subclass of SequentialType for pointer types.</dd>
  2527. <dt><tt>VectorType</tt></dt>
  2528. <dd>Subclass of SequentialType for vector types. A
  2529. vector type is similar to an ArrayType but is distinguished because it is
  2530. a first class type whereas ArrayType is not. Vector types are used for
  2531. vector operations and are usually small vectors of of an integer or floating
  2532. point type.</dd>
  2533. <dt><tt>StructType</tt></dt>
  2534. <dd>Subclass of DerivedTypes for struct types.</dd>
  2535. <dt><tt><a name="FunctionType">FunctionType</a></tt></dt>
  2536. <dd>Subclass of DerivedTypes for function types.
  2537. <ul>
  2538. <li><tt>bool isVarArg() const</tt>: Returns true if it's a vararg
  2539. function</li>
  2540. <li><tt> const Type * getReturnType() const</tt>: Returns the
  2541. return type of the function.</li>
  2542. <li><tt>const Type * getParamType (unsigned i)</tt>: Returns
  2543. the type of the ith parameter.</li>
  2544. <li><tt> const unsigned getNumParams() const</tt>: Returns the
  2545. number of formal parameters.</li>
  2546. </ul>
  2547. </dd>
  2548. <dt><tt>OpaqueType</tt></dt>
  2549. <dd>Sublcass of DerivedType for abstract types. This class
  2550. defines no content and is used as a placeholder for some other type. Note
  2551. that OpaqueType is used (temporarily) during type resolution for forward
  2552. references of types. Once the referenced type is resolved, the OpaqueType
  2553. is replaced with the actual type. OpaqueType can also be used for data
  2554. abstraction. At link time opaque types can be resolved to actual types
  2555. of the same name.</dd>
  2556. </dl>
  2557. </div>
  2558. <!-- ======================================================================= -->
  2559. <div class="doc_subsection">
  2560. <a name="Module">The <tt>Module</tt> class</a>
  2561. </div>
  2562. <div class="doc_text">
  2563. <p><tt>#include "<a
  2564. href="/doxygen/Module_8h-source.html">llvm/Module.h</a>"</tt><br> doxygen info:
  2565. <a href="/doxygen/classllvm_1_1Module.html">Module Class</a></p>
  2566. <p>The <tt>Module</tt> class represents the top level structure present in LLVM
  2567. programs. An LLVM module is effectively either a translation unit of the
  2568. original program or a combination of several translation units merged by the
  2569. linker. The <tt>Module</tt> class keeps track of a list of <a
  2570. href="#Function"><tt>Function</tt></a>s, a list of <a
  2571. href="#GlobalVariable"><tt>GlobalVariable</tt></a>s, and a <a
  2572. href="#SymbolTable"><tt>SymbolTable</tt></a>. Additionally, it contains a few
  2573. helpful member functions that try to make common operations easy.</p>
  2574. </div>
  2575. <!-- _______________________________________________________________________ -->
  2576. <div class="doc_subsubsection">
  2577. <a name="m_Module">Important Public Members of the <tt>Module</tt> class</a>
  2578. </div>
  2579. <div class="doc_text">
  2580. <ul>
  2581. <li><tt>Module::Module(std::string name = "")</tt></li>
  2582. </ul>
  2583. <p>Constructing a <a href="#Module">Module</a> is easy. You can optionally
  2584. provide a name for it (probably based on the name of the translation unit).</p>
  2585. <ul>
  2586. <li><tt>Module::iterator</tt> - Typedef for function list iterator<br>
  2587. <tt>Module::const_iterator</tt> - Typedef for const_iterator.<br>
  2588. <tt>begin()</tt>, <tt>end()</tt>
  2589. <tt>size()</tt>, <tt>empty()</tt>
  2590. <p>These are forwarding methods that make it easy to access the contents of
  2591. a <tt>Module</tt> object's <a href="#Function"><tt>Function</tt></a>
  2592. list.</p></li>
  2593. <li><tt>Module::FunctionListType &amp;getFunctionList()</tt>
  2594. <p> Returns the list of <a href="#Function"><tt>Function</tt></a>s. This is
  2595. necessary to use when you need to update the list or perform a complex
  2596. action that doesn't have a forwarding method.</p>
  2597. <p><!-- Global Variable --></p></li>
  2598. </ul>
  2599. <hr>
  2600. <ul>
  2601. <li><tt>Module::global_iterator</tt> - Typedef for global variable list iterator<br>
  2602. <tt>Module::const_global_iterator</tt> - Typedef for const_iterator.<br>
  2603. <tt>global_begin()</tt>, <tt>global_end()</tt>
  2604. <tt>global_size()</tt>, <tt>global_empty()</tt>
  2605. <p> These are forwarding methods that make it easy to access the contents of
  2606. a <tt>Module</tt> object's <a
  2607. href="#GlobalVariable"><tt>GlobalVariable</tt></a> list.</p></li>
  2608. <li><tt>Module::GlobalListType &amp;getGlobalList()</tt>
  2609. <p>Returns the list of <a
  2610. href="#GlobalVariable"><tt>GlobalVariable</tt></a>s. This is necessary to
  2611. use when you need to update the list or perform a complex action that
  2612. doesn't have a forwarding method.</p>
  2613. <p><!-- Symbol table stuff --> </p></li>
  2614. </ul>
  2615. <hr>
  2616. <ul>
  2617. <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
  2618. <p>Return a reference to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
  2619. for this <tt>Module</tt>.</p>
  2620. <p><!-- Convenience methods --></p></li>
  2621. </ul>
  2622. <hr>
  2623. <ul>
  2624. <li><tt><a href="#Function">Function</a> *getFunction(const std::string
  2625. &amp;Name, const <a href="#FunctionType">FunctionType</a> *Ty)</tt>
  2626. <p>Look up the specified function in the <tt>Module</tt> <a
  2627. href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, return
  2628. <tt>null</tt>.</p></li>
  2629. <li><tt><a href="#Function">Function</a> *getOrInsertFunction(const
  2630. std::string &amp;Name, const <a href="#FunctionType">FunctionType</a> *T)</tt>
  2631. <p>Look up the specified function in the <tt>Module</tt> <a
  2632. href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, add an
  2633. external declaration for the function and return it.</p></li>
  2634. <li><tt>std::string getTypeName(const <a href="#Type">Type</a> *Ty)</tt>
  2635. <p>If there is at least one entry in the <a
  2636. href="#SymbolTable"><tt>SymbolTable</tt></a> for the specified <a
  2637. href="#Type"><tt>Type</tt></a>, return it. Otherwise return the empty
  2638. string.</p></li>
  2639. <li><tt>bool addTypeName(const std::string &amp;Name, const <a
  2640. href="#Type">Type</a> *Ty)</tt>
  2641. <p>Insert an entry in the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
  2642. mapping <tt>Name</tt> to <tt>Ty</tt>. If there is already an entry for this
  2643. name, true is returned and the <a
  2644. href="#SymbolTable"><tt>SymbolTable</tt></a> is not modified.</p></li>
  2645. </ul>
  2646. </div>
  2647. <!-- ======================================================================= -->
  2648. <div class="doc_subsection">
  2649. <a name="Value">The <tt>Value</tt> class</a>
  2650. </div>
  2651. <div class="doc_text">
  2652. <p><tt>#include "<a href="/doxygen/Value_8h-source.html">llvm/Value.h</a>"</tt>
  2653. <br>
  2654. doxygen info: <a href="/doxygen/classllvm_1_1Value.html">Value Class</a></p>
  2655. <p>The <tt>Value</tt> class is the most important class in the LLVM Source
  2656. base. It represents a typed value that may be used (among other things) as an
  2657. operand to an instruction. There are many different types of <tt>Value</tt>s,
  2658. such as <a href="#Constant"><tt>Constant</tt></a>s,<a
  2659. href="#Argument"><tt>Argument</tt></a>s. Even <a
  2660. href="#Instruction"><tt>Instruction</tt></a>s and <a
  2661. href="#Function"><tt>Function</tt></a>s are <tt>Value</tt>s.</p>
  2662. <p>A particular <tt>Value</tt> may be used many times in the LLVM representation
  2663. for a program. For example, an incoming argument to a function (represented
  2664. with an instance of the <a href="#Argument">Argument</a> class) is "used" by
  2665. every instruction in the function that references the argument. To keep track
  2666. of this relationship, the <tt>Value</tt> class keeps a list of all of the <a
  2667. href="#User"><tt>User</tt></a>s that is using it (the <a
  2668. href="#User"><tt>User</tt></a> class is a base class for all nodes in the LLVM
  2669. graph that can refer to <tt>Value</tt>s). This use list is how LLVM represents
  2670. def-use information in the program, and is accessible through the <tt>use_</tt>*
  2671. methods, shown below.</p>
  2672. <p>Because LLVM is a typed representation, every LLVM <tt>Value</tt> is typed,
  2673. and this <a href="#Type">Type</a> is available through the <tt>getType()</tt>
  2674. method. In addition, all LLVM values can be named. The "name" of the
  2675. <tt>Value</tt> is a symbolic string printed in the LLVM code:</p>
  2676. <div class="doc_code">
  2677. <pre>
  2678. %<b>foo</b> = add i32 1, 2
  2679. </pre>
  2680. </div>
  2681. <p><a name="nameWarning">The name of this instruction is "foo".</a> <b>NOTE</b>
  2682. that the name of any value may be missing (an empty string), so names should
  2683. <b>ONLY</b> be used for debugging (making the source code easier to read,
  2684. debugging printouts), they should not be used to keep track of values or map
  2685. between them. For this purpose, use a <tt>std::map</tt> of pointers to the
  2686. <tt>Value</tt> itself instead.</p>
  2687. <p>One important aspect of LLVM is that there is no distinction between an SSA
  2688. variable and the operation that produces it. Because of this, any reference to
  2689. the value produced by an instruction (or the value available as an incoming
  2690. argument, for example) is represented as a direct pointer to the instance of
  2691. the class that
  2692. represents this value. Although this may take some getting used to, it
  2693. simplifies the representation and makes it easier to manipulate.</p>
  2694. </div>
  2695. <!-- _______________________________________________________________________ -->
  2696. <div class="doc_subsubsection">
  2697. <a name="m_Value">Important Public Members of the <tt>Value</tt> class</a>
  2698. </div>
  2699. <div class="doc_text">
  2700. <ul>
  2701. <li><tt>Value::use_iterator</tt> - Typedef for iterator over the
  2702. use-list<br>
  2703. <tt>Value::const_use_iterator</tt> - Typedef for const_iterator over
  2704. the use-list<br>
  2705. <tt>unsigned use_size()</tt> - Returns the number of users of the
  2706. value.<br>
  2707. <tt>bool use_empty()</tt> - Returns true if there are no users.<br>
  2708. <tt>use_iterator use_begin()</tt> - Get an iterator to the start of
  2709. the use-list.<br>
  2710. <tt>use_iterator use_end()</tt> - Get an iterator to the end of the
  2711. use-list.<br>
  2712. <tt><a href="#User">User</a> *use_back()</tt> - Returns the last
  2713. element in the list.
  2714. <p> These methods are the interface to access the def-use
  2715. information in LLVM. As with all other iterators in LLVM, the naming
  2716. conventions follow the conventions defined by the <a href="#stl">STL</a>.</p>
  2717. </li>
  2718. <li><tt><a href="#Type">Type</a> *getType() const</tt>
  2719. <p>This method returns the Type of the Value.</p>
  2720. </li>
  2721. <li><tt>bool hasName() const</tt><br>
  2722. <tt>std::string getName() const</tt><br>
  2723. <tt>void setName(const std::string &amp;Name)</tt>
  2724. <p> This family of methods is used to access and assign a name to a <tt>Value</tt>,
  2725. be aware of the <a href="#nameWarning">precaution above</a>.</p>
  2726. </li>
  2727. <li><tt>void replaceAllUsesWith(Value *V)</tt>
  2728. <p>This method traverses the use list of a <tt>Value</tt> changing all <a
  2729. href="#User"><tt>User</tt>s</a> of the current value to refer to
  2730. "<tt>V</tt>" instead. For example, if you detect that an instruction always
  2731. produces a constant value (for example through constant folding), you can
  2732. replace all uses of the instruction with the constant like this:</p>
  2733. <div class="doc_code">
  2734. <pre>
  2735. Inst-&gt;replaceAllUsesWith(ConstVal);
  2736. </pre>
  2737. </div>
  2738. </ul>
  2739. </div>
  2740. <!-- ======================================================================= -->
  2741. <div class="doc_subsection">
  2742. <a name="User">The <tt>User</tt> class</a>
  2743. </div>
  2744. <div class="doc_text">
  2745. <p>
  2746. <tt>#include "<a href="/doxygen/User_8h-source.html">llvm/User.h</a>"</tt><br>
  2747. doxygen info: <a href="/doxygen/classllvm_1_1User.html">User Class</a><br>
  2748. Superclass: <a href="#Value"><tt>Value</tt></a></p>
  2749. <p>The <tt>User</tt> class is the common base class of all LLVM nodes that may
  2750. refer to <a href="#Value"><tt>Value</tt></a>s. It exposes a list of "Operands"
  2751. that are all of the <a href="#Value"><tt>Value</tt></a>s that the User is
  2752. referring to. The <tt>User</tt> class itself is a subclass of
  2753. <tt>Value</tt>.</p>
  2754. <p>The operands of a <tt>User</tt> point directly to the LLVM <a
  2755. href="#Value"><tt>Value</tt></a> that it refers to. Because LLVM uses Static
  2756. Single Assignment (SSA) form, there can only be one definition referred to,
  2757. allowing this direct connection. This connection provides the use-def
  2758. information in LLVM.</p>
  2759. </div>
  2760. <!-- _______________________________________________________________________ -->
  2761. <div class="doc_subsubsection">
  2762. <a name="m_User">Important Public Members of the <tt>User</tt> class</a>
  2763. </div>
  2764. <div class="doc_text">
  2765. <p>The <tt>User</tt> class exposes the operand list in two ways: through
  2766. an index access interface and through an iterator based interface.</p>
  2767. <ul>
  2768. <li><tt>Value *getOperand(unsigned i)</tt><br>
  2769. <tt>unsigned getNumOperands()</tt>
  2770. <p> These two methods expose the operands of the <tt>User</tt> in a
  2771. convenient form for direct access.</p></li>
  2772. <li><tt>User::op_iterator</tt> - Typedef for iterator over the operand
  2773. list<br>
  2774. <tt>op_iterator op_begin()</tt> - Get an iterator to the start of
  2775. the operand list.<br>
  2776. <tt>op_iterator op_end()</tt> - Get an iterator to the end of the
  2777. operand list.
  2778. <p> Together, these methods make up the iterator based interface to
  2779. the operands of a <tt>User</tt>.</p></li>
  2780. </ul>
  2781. </div>
  2782. <!-- ======================================================================= -->
  2783. <div class="doc_subsection">
  2784. <a name="Instruction">The <tt>Instruction</tt> class</a>
  2785. </div>
  2786. <div class="doc_text">
  2787. <p><tt>#include "</tt><tt><a
  2788. href="/doxygen/Instruction_8h-source.html">llvm/Instruction.h</a>"</tt><br>
  2789. doxygen info: <a href="/doxygen/classllvm_1_1Instruction.html">Instruction Class</a><br>
  2790. Superclasses: <a href="#User"><tt>User</tt></a>, <a
  2791. href="#Value"><tt>Value</tt></a></p>
  2792. <p>The <tt>Instruction</tt> class is the common base class for all LLVM
  2793. instructions. It provides only a few methods, but is a very commonly used
  2794. class. The primary data tracked by the <tt>Instruction</tt> class itself is the
  2795. opcode (instruction type) and the parent <a
  2796. href="#BasicBlock"><tt>BasicBlock</tt></a> the <tt>Instruction</tt> is embedded
  2797. into. To represent a specific type of instruction, one of many subclasses of
  2798. <tt>Instruction</tt> are used.</p>
  2799. <p> Because the <tt>Instruction</tt> class subclasses the <a
  2800. href="#User"><tt>User</tt></a> class, its operands can be accessed in the same
  2801. way as for other <a href="#User"><tt>User</tt></a>s (with the
  2802. <tt>getOperand()</tt>/<tt>getNumOperands()</tt> and
  2803. <tt>op_begin()</tt>/<tt>op_end()</tt> methods).</p> <p> An important file for
  2804. the <tt>Instruction</tt> class is the <tt>llvm/Instruction.def</tt> file. This
  2805. file contains some meta-data about the various different types of instructions
  2806. in LLVM. It describes the enum values that are used as opcodes (for example
  2807. <tt>Instruction::Add</tt> and <tt>Instruction::ICmp</tt>), as well as the
  2808. concrete sub-classes of <tt>Instruction</tt> that implement the instruction (for
  2809. example <tt><a href="#BinaryOperator">BinaryOperator</a></tt> and <tt><a
  2810. href="#CmpInst">CmpInst</a></tt>). Unfortunately, the use of macros in
  2811. this file confuses doxygen, so these enum values don't show up correctly in the
  2812. <a href="/doxygen/classllvm_1_1Instruction.html">doxygen output</a>.</p>
  2813. </div>
  2814. <!-- _______________________________________________________________________ -->
  2815. <div class="doc_subsubsection">
  2816. <a name="s_Instruction">Important Subclasses of the <tt>Instruction</tt>
  2817. class</a>
  2818. </div>
  2819. <div class="doc_text">
  2820. <ul>
  2821. <li><tt><a name="BinaryOperator">BinaryOperator</a></tt>
  2822. <p>This subclasses represents all two operand instructions whose operands
  2823. must be the same type, except for the comparison instructions.</p></li>
  2824. <li><tt><a name="CastInst">CastInst</a></tt>
  2825. <p>This subclass is the parent of the 12 casting instructions. It provides
  2826. common operations on cast instructions.</p>
  2827. <li><tt><a name="CmpInst">CmpInst</a></tt>
  2828. <p>This subclass respresents the two comparison instructions,
  2829. <a href="LangRef.html#i_icmp">ICmpInst</a> (integer opreands), and
  2830. <a href="LangRef.html#i_fcmp">FCmpInst</a> (floating point operands).</p>
  2831. <li><tt><a name="TerminatorInst">TerminatorInst</a></tt>
  2832. <p>This subclass is the parent of all terminator instructions (those which
  2833. can terminate a block).</p>
  2834. </ul>
  2835. </div>
  2836. <!-- _______________________________________________________________________ -->
  2837. <div class="doc_subsubsection">
  2838. <a name="m_Instruction">Important Public Members of the <tt>Instruction</tt>
  2839. class</a>
  2840. </div>
  2841. <div class="doc_text">
  2842. <ul>
  2843. <li><tt><a href="#BasicBlock">BasicBlock</a> *getParent()</tt>
  2844. <p>Returns the <a href="#BasicBlock"><tt>BasicBlock</tt></a> that
  2845. this <tt>Instruction</tt> is embedded into.</p></li>
  2846. <li><tt>bool mayWriteToMemory()</tt>
  2847. <p>Returns true if the instruction writes to memory, i.e. it is a
  2848. <tt>call</tt>,<tt>free</tt>,<tt>invoke</tt>, or <tt>store</tt>.</p></li>
  2849. <li><tt>unsigned getOpcode()</tt>
  2850. <p>Returns the opcode for the <tt>Instruction</tt>.</p></li>
  2851. <li><tt><a href="#Instruction">Instruction</a> *clone() const</tt>
  2852. <p>Returns another instance of the specified instruction, identical
  2853. in all ways to the original except that the instruction has no parent
  2854. (ie it's not embedded into a <a href="#BasicBlock"><tt>BasicBlock</tt></a>),
  2855. and it has no name</p></li>
  2856. </ul>
  2857. </div>
  2858. <!-- ======================================================================= -->
  2859. <div class="doc_subsection">
  2860. <a name="Constant">The <tt>Constant</tt> class and subclasses</a>
  2861. </div>
  2862. <div class="doc_text">
  2863. <p>Constant represents a base class for different types of constants. It
  2864. is subclassed by ConstantInt, ConstantArray, etc. for representing
  2865. the various types of Constants. <a href="#GlobalValue">GlobalValue</a> is also
  2866. a subclass, which represents the address of a global variable or function.
  2867. </p>
  2868. </div>
  2869. <!-- _______________________________________________________________________ -->
  2870. <div class="doc_subsubsection">Important Subclasses of Constant </div>
  2871. <div class="doc_text">
  2872. <ul>
  2873. <li>ConstantInt : This subclass of Constant represents an integer constant of
  2874. any width.
  2875. <ul>
  2876. <li><tt>const APInt&amp; getValue() const</tt>: Returns the underlying
  2877. value of this constant, an APInt value.</li>
  2878. <li><tt>int64_t getSExtValue() const</tt>: Converts the underlying APInt
  2879. value to an int64_t via sign extension. If the value (not the bit width)
  2880. of the APInt is too large to fit in an int64_t, an assertion will result.
  2881. For this reason, use of this method is discouraged.</li>
  2882. <li><tt>uint64_t getZExtValue() const</tt>: Converts the underlying APInt
  2883. value to a uint64_t via zero extension. IF the value (not the bit width)
  2884. of the APInt is too large to fit in a uint64_t, an assertion will result.
  2885. For this reason, use of this method is discouraged.</li>
  2886. <li><tt>static ConstantInt* get(const APInt&amp; Val)</tt>: Returns the
  2887. ConstantInt object that represents the value provided by <tt>Val</tt>.
  2888. The type is implied as the IntegerType that corresponds to the bit width
  2889. of <tt>Val</tt>.</li>
  2890. <li><tt>static ConstantInt* get(const Type *Ty, uint64_t Val)</tt>:
  2891. Returns the ConstantInt object that represents the value provided by
  2892. <tt>Val</tt> for integer type <tt>Ty</tt>.</li>
  2893. </ul>
  2894. </li>
  2895. <li>ConstantFP : This class represents a floating point constant.
  2896. <ul>
  2897. <li><tt>double getValue() const</tt>: Returns the underlying value of
  2898. this constant. </li>
  2899. </ul>
  2900. </li>
  2901. <li>ConstantArray : This represents a constant array.
  2902. <ul>
  2903. <li><tt>const std::vector&lt;Use&gt; &amp;getValues() const</tt>: Returns
  2904. a vector of component constants that makeup this array. </li>
  2905. </ul>
  2906. </li>
  2907. <li>ConstantStruct : This represents a constant struct.
  2908. <ul>
  2909. <li><tt>const std::vector&lt;Use&gt; &amp;getValues() const</tt>: Returns
  2910. a vector of component constants that makeup this array. </li>
  2911. </ul>
  2912. </li>
  2913. <li>GlobalValue : This represents either a global variable or a function. In
  2914. either case, the value is a constant fixed address (after linking).
  2915. </li>
  2916. </ul>
  2917. </div>
  2918. <!-- ======================================================================= -->
  2919. <div class="doc_subsection">
  2920. <a name="GlobalValue">The <tt>GlobalValue</tt> class</a>
  2921. </div>
  2922. <div class="doc_text">
  2923. <p><tt>#include "<a
  2924. href="/doxygen/GlobalValue_8h-source.html">llvm/GlobalValue.h</a>"</tt><br>
  2925. doxygen info: <a href="/doxygen/classllvm_1_1GlobalValue.html">GlobalValue
  2926. Class</a><br>
  2927. Superclasses: <a href="#Constant"><tt>Constant</tt></a>,
  2928. <a href="#User"><tt>User</tt></a>, <a href="#Value"><tt>Value</tt></a></p>
  2929. <p>Global values (<a href="#GlobalVariable"><tt>GlobalVariable</tt></a>s or <a
  2930. href="#Function"><tt>Function</tt></a>s) are the only LLVM values that are
  2931. visible in the bodies of all <a href="#Function"><tt>Function</tt></a>s.
  2932. Because they are visible at global scope, they are also subject to linking with
  2933. other globals defined in different translation units. To control the linking
  2934. process, <tt>GlobalValue</tt>s know their linkage rules. Specifically,
  2935. <tt>GlobalValue</tt>s know whether they have internal or external linkage, as
  2936. defined by the <tt>LinkageTypes</tt> enumeration.</p>
  2937. <p>If a <tt>GlobalValue</tt> has internal linkage (equivalent to being
  2938. <tt>static</tt> in C), it is not visible to code outside the current translation
  2939. unit, and does not participate in linking. If it has external linkage, it is
  2940. visible to external code, and does participate in linking. In addition to
  2941. linkage information, <tt>GlobalValue</tt>s keep track of which <a
  2942. href="#Module"><tt>Module</tt></a> they are currently part of.</p>
  2943. <p>Because <tt>GlobalValue</tt>s are memory objects, they are always referred to
  2944. by their <b>address</b>. As such, the <a href="#Type"><tt>Type</tt></a> of a
  2945. global is always a pointer to its contents. It is important to remember this
  2946. when using the <tt>GetElementPtrInst</tt> instruction because this pointer must
  2947. be dereferenced first. For example, if you have a <tt>GlobalVariable</tt> (a
  2948. subclass of <tt>GlobalValue)</tt> that is an array of 24 ints, type <tt>[24 x
  2949. i32]</tt>, then the <tt>GlobalVariable</tt> is a pointer to that array. Although
  2950. the address of the first element of this array and the value of the
  2951. <tt>GlobalVariable</tt> are the same, they have different types. The
  2952. <tt>GlobalVariable</tt>'s type is <tt>[24 x i32]</tt>. The first element's type
  2953. is <tt>i32.</tt> Because of this, accessing a global value requires you to
  2954. dereference the pointer with <tt>GetElementPtrInst</tt> first, then its elements
  2955. can be accessed. This is explained in the <a href="LangRef.html#globalvars">LLVM
  2956. Language Reference Manual</a>.</p>
  2957. </div>
  2958. <!-- _______________________________________________________________________ -->
  2959. <div class="doc_subsubsection">
  2960. <a name="m_GlobalValue">Important Public Members of the <tt>GlobalValue</tt>
  2961. class</a>
  2962. </div>
  2963. <div class="doc_text">
  2964. <ul>
  2965. <li><tt>bool hasInternalLinkage() const</tt><br>
  2966. <tt>bool hasExternalLinkage() const</tt><br>
  2967. <tt>void setInternalLinkage(bool HasInternalLinkage)</tt>
  2968. <p> These methods manipulate the linkage characteristics of the <tt>GlobalValue</tt>.</p>
  2969. <p> </p>
  2970. </li>
  2971. <li><tt><a href="#Module">Module</a> *getParent()</tt>
  2972. <p> This returns the <a href="#Module"><tt>Module</tt></a> that the
  2973. GlobalValue is currently embedded into.</p></li>
  2974. </ul>
  2975. </div>
  2976. <!-- ======================================================================= -->
  2977. <div class="doc_subsection">
  2978. <a name="Function">The <tt>Function</tt> class</a>
  2979. </div>
  2980. <div class="doc_text">
  2981. <p><tt>#include "<a
  2982. href="/doxygen/Function_8h-source.html">llvm/Function.h</a>"</tt><br> doxygen
  2983. info: <a href="/doxygen/classllvm_1_1Function.html">Function Class</a><br>
  2984. Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>,
  2985. <a href="#Constant"><tt>Constant</tt></a>,
  2986. <a href="#User"><tt>User</tt></a>,
  2987. <a href="#Value"><tt>Value</tt></a></p>
  2988. <p>The <tt>Function</tt> class represents a single procedure in LLVM. It is
  2989. actually one of the more complex classes in the LLVM hierarchy because it must
  2990. keep track of a large amount of data. The <tt>Function</tt> class keeps track
  2991. of a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, a list of formal
  2992. <a href="#Argument"><tt>Argument</tt></a>s, and a
  2993. <a href="#SymbolTable"><tt>SymbolTable</tt></a>.</p>
  2994. <p>The list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s is the most
  2995. commonly used part of <tt>Function</tt> objects. The list imposes an implicit
  2996. ordering of the blocks in the function, which indicate how the code will be
  2997. laid out by the backend. Additionally, the first <a
  2998. href="#BasicBlock"><tt>BasicBlock</tt></a> is the implicit entry node for the
  2999. <tt>Function</tt>. It is not legal in LLVM to explicitly branch to this initial
  3000. block. There are no implicit exit nodes, and in fact there may be multiple exit
  3001. nodes from a single <tt>Function</tt>. If the <a
  3002. href="#BasicBlock"><tt>BasicBlock</tt></a> list is empty, this indicates that
  3003. the <tt>Function</tt> is actually a function declaration: the actual body of the
  3004. function hasn't been linked in yet.</p>
  3005. <p>In addition to a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, the
  3006. <tt>Function</tt> class also keeps track of the list of formal <a
  3007. href="#Argument"><tt>Argument</tt></a>s that the function receives. This
  3008. container manages the lifetime of the <a href="#Argument"><tt>Argument</tt></a>
  3009. nodes, just like the <a href="#BasicBlock"><tt>BasicBlock</tt></a> list does for
  3010. the <a href="#BasicBlock"><tt>BasicBlock</tt></a>s.</p>
  3011. <p>The <a href="#SymbolTable"><tt>SymbolTable</tt></a> is a very rarely used
  3012. LLVM feature that is only used when you have to look up a value by name. Aside
  3013. from that, the <a href="#SymbolTable"><tt>SymbolTable</tt></a> is used
  3014. internally to make sure that there are not conflicts between the names of <a
  3015. href="#Instruction"><tt>Instruction</tt></a>s, <a
  3016. href="#BasicBlock"><tt>BasicBlock</tt></a>s, or <a
  3017. href="#Argument"><tt>Argument</tt></a>s in the function body.</p>
  3018. <p>Note that <tt>Function</tt> is a <a href="#GlobalValue">GlobalValue</a>
  3019. and therefore also a <a href="#Constant">Constant</a>. The value of the function
  3020. is its address (after linking) which is guaranteed to be constant.</p>
  3021. </div>
  3022. <!-- _______________________________________________________________________ -->
  3023. <div class="doc_subsubsection">
  3024. <a name="m_Function">Important Public Members of the <tt>Function</tt>
  3025. class</a>
  3026. </div>
  3027. <div class="doc_text">
  3028. <ul>
  3029. <li><tt>Function(const </tt><tt><a href="#FunctionType">FunctionType</a>
  3030. *Ty, LinkageTypes Linkage, const std::string &amp;N = "", Module* Parent = 0)</tt>
  3031. <p>Constructor used when you need to create new <tt>Function</tt>s to add
  3032. the the program. The constructor must specify the type of the function to
  3033. create and what type of linkage the function should have. The <a
  3034. href="#FunctionType"><tt>FunctionType</tt></a> argument
  3035. specifies the formal arguments and return value for the function. The same
  3036. <a href="#FunctionType"><tt>FunctionType</tt></a> value can be used to
  3037. create multiple functions. The <tt>Parent</tt> argument specifies the Module
  3038. in which the function is defined. If this argument is provided, the function
  3039. will automatically be inserted into that module's list of
  3040. functions.</p></li>
  3041. <li><tt>bool isDeclaration()</tt>
  3042. <p>Return whether or not the <tt>Function</tt> has a body defined. If the
  3043. function is "external", it does not have a body, and thus must be resolved
  3044. by linking with a function defined in a different translation unit.</p></li>
  3045. <li><tt>Function::iterator</tt> - Typedef for basic block list iterator<br>
  3046. <tt>Function::const_iterator</tt> - Typedef for const_iterator.<br>
  3047. <tt>begin()</tt>, <tt>end()</tt>
  3048. <tt>size()</tt>, <tt>empty()</tt>
  3049. <p>These are forwarding methods that make it easy to access the contents of
  3050. a <tt>Function</tt> object's <a href="#BasicBlock"><tt>BasicBlock</tt></a>
  3051. list.</p></li>
  3052. <li><tt>Function::BasicBlockListType &amp;getBasicBlockList()</tt>
  3053. <p>Returns the list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s. This
  3054. is necessary to use when you need to update the list or perform a complex
  3055. action that doesn't have a forwarding method.</p></li>
  3056. <li><tt>Function::arg_iterator</tt> - Typedef for the argument list
  3057. iterator<br>
  3058. <tt>Function::const_arg_iterator</tt> - Typedef for const_iterator.<br>
  3059. <tt>arg_begin()</tt>, <tt>arg_end()</tt>
  3060. <tt>arg_size()</tt>, <tt>arg_empty()</tt>
  3061. <p>These are forwarding methods that make it easy to access the contents of
  3062. a <tt>Function</tt> object's <a href="#Argument"><tt>Argument</tt></a>
  3063. list.</p></li>
  3064. <li><tt>Function::ArgumentListType &amp;getArgumentList()</tt>
  3065. <p>Returns the list of <a href="#Argument"><tt>Argument</tt></a>s. This is
  3066. necessary to use when you need to update the list or perform a complex
  3067. action that doesn't have a forwarding method.</p></li>
  3068. <li><tt><a href="#BasicBlock">BasicBlock</a> &amp;getEntryBlock()</tt>
  3069. <p>Returns the entry <a href="#BasicBlock"><tt>BasicBlock</tt></a> for the
  3070. function. Because the entry block for the function is always the first
  3071. block, this returns the first block of the <tt>Function</tt>.</p></li>
  3072. <li><tt><a href="#Type">Type</a> *getReturnType()</tt><br>
  3073. <tt><a href="#FunctionType">FunctionType</a> *getFunctionType()</tt>
  3074. <p>This traverses the <a href="#Type"><tt>Type</tt></a> of the
  3075. <tt>Function</tt> and returns the return type of the function, or the <a
  3076. href="#FunctionType"><tt>FunctionType</tt></a> of the actual
  3077. function.</p></li>
  3078. <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
  3079. <p> Return a pointer to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
  3080. for this <tt>Function</tt>.</p></li>
  3081. </ul>
  3082. </div>
  3083. <!-- ======================================================================= -->
  3084. <div class="doc_subsection">
  3085. <a name="GlobalVariable">The <tt>GlobalVariable</tt> class</a>
  3086. </div>
  3087. <div class="doc_text">
  3088. <p><tt>#include "<a
  3089. href="/doxygen/GlobalVariable_8h-source.html">llvm/GlobalVariable.h</a>"</tt>
  3090. <br>
  3091. doxygen info: <a href="/doxygen/classllvm_1_1GlobalVariable.html">GlobalVariable
  3092. Class</a><br>
  3093. Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>,
  3094. <a href="#Constant"><tt>Constant</tt></a>,
  3095. <a href="#User"><tt>User</tt></a>,
  3096. <a href="#Value"><tt>Value</tt></a></p>
  3097. <p>Global variables are represented with the (surprise surprise)
  3098. <tt>GlobalVariable</tt> class. Like functions, <tt>GlobalVariable</tt>s are also
  3099. subclasses of <a href="#GlobalValue"><tt>GlobalValue</tt></a>, and as such are
  3100. always referenced by their address (global values must live in memory, so their
  3101. "name" refers to their constant address). See
  3102. <a href="#GlobalValue"><tt>GlobalValue</tt></a> for more on this. Global
  3103. variables may have an initial value (which must be a
  3104. <a href="#Constant"><tt>Constant</tt></a>), and if they have an initializer,
  3105. they may be marked as "constant" themselves (indicating that their contents
  3106. never change at runtime).</p>
  3107. </div>
  3108. <!-- _______________________________________________________________________ -->
  3109. <div class="doc_subsubsection">
  3110. <a name="m_GlobalVariable">Important Public Members of the
  3111. <tt>GlobalVariable</tt> class</a>
  3112. </div>
  3113. <div class="doc_text">
  3114. <ul>
  3115. <li><tt>GlobalVariable(const </tt><tt><a href="#Type">Type</a> *Ty, bool
  3116. isConstant, LinkageTypes&amp; Linkage, <a href="#Constant">Constant</a>
  3117. *Initializer = 0, const std::string &amp;Name = "", Module* Parent = 0)</tt>
  3118. <p>Create a new global variable of the specified type. If
  3119. <tt>isConstant</tt> is true then the global variable will be marked as
  3120. unchanging for the program. The Linkage parameter specifies the type of
  3121. linkage (internal, external, weak, linkonce, appending) for the variable.
  3122. If the linkage is InternalLinkage, WeakAnyLinkage, WeakODRLinkage,
  3123. LinkOnceAnyLinkage or LinkOnceODRLinkage,&nbsp; then the resultant
  3124. global variable will have internal linkage. AppendingLinkage concatenates
  3125. together all instances (in different translation units) of the variable
  3126. into a single variable but is only applicable to arrays. &nbsp;See
  3127. the <a href="LangRef.html#modulestructure">LLVM Language Reference</a> for
  3128. further details on linkage types. Optionally an initializer, a name, and the
  3129. module to put the variable into may be specified for the global variable as
  3130. well.</p></li>
  3131. <li><tt>bool isConstant() const</tt>
  3132. <p>Returns true if this is a global variable that is known not to
  3133. be modified at runtime.</p></li>
  3134. <li><tt>bool hasInitializer()</tt>
  3135. <p>Returns true if this <tt>GlobalVariable</tt> has an intializer.</p></li>
  3136. <li><tt><a href="#Constant">Constant</a> *getInitializer()</tt>
  3137. <p>Returns the initial value for a <tt>GlobalVariable</tt>. It is not legal
  3138. to call this method if there is no initializer.</p></li>
  3139. </ul>
  3140. </div>
  3141. <!-- ======================================================================= -->
  3142. <div class="doc_subsection">
  3143. <a name="BasicBlock">The <tt>BasicBlock</tt> class</a>
  3144. </div>
  3145. <div class="doc_text">
  3146. <p><tt>#include "<a
  3147. href="/doxygen/BasicBlock_8h-source.html">llvm/BasicBlock.h</a>"</tt><br>
  3148. doxygen info: <a href="/doxygen/classllvm_1_1BasicBlock.html">BasicBlock
  3149. Class</a><br>
  3150. Superclass: <a href="#Value"><tt>Value</tt></a></p>
  3151. <p>This class represents a single entry multiple exit section of the code,
  3152. commonly known as a basic block by the compiler community. The
  3153. <tt>BasicBlock</tt> class maintains a list of <a
  3154. href="#Instruction"><tt>Instruction</tt></a>s, which form the body of the block.
  3155. Matching the language definition, the last element of this list of instructions
  3156. is always a terminator instruction (a subclass of the <a
  3157. href="#TerminatorInst"><tt>TerminatorInst</tt></a> class).</p>
  3158. <p>In addition to tracking the list of instructions that make up the block, the
  3159. <tt>BasicBlock</tt> class also keeps track of the <a
  3160. href="#Function"><tt>Function</tt></a> that it is embedded into.</p>
  3161. <p>Note that <tt>BasicBlock</tt>s themselves are <a
  3162. href="#Value"><tt>Value</tt></a>s, because they are referenced by instructions
  3163. like branches and can go in the switch tables. <tt>BasicBlock</tt>s have type
  3164. <tt>label</tt>.</p>
  3165. </div>
  3166. <!-- _______________________________________________________________________ -->
  3167. <div class="doc_subsubsection">
  3168. <a name="m_BasicBlock">Important Public Members of the <tt>BasicBlock</tt>
  3169. class</a>
  3170. </div>
  3171. <div class="doc_text">
  3172. <ul>
  3173. <li><tt>BasicBlock(const std::string &amp;Name = "", </tt><tt><a
  3174. href="#Function">Function</a> *Parent = 0)</tt>
  3175. <p>The <tt>BasicBlock</tt> constructor is used to create new basic blocks for
  3176. insertion into a function. The constructor optionally takes a name for the new
  3177. block, and a <a href="#Function"><tt>Function</tt></a> to insert it into. If
  3178. the <tt>Parent</tt> parameter is specified, the new <tt>BasicBlock</tt> is
  3179. automatically inserted at the end of the specified <a
  3180. href="#Function"><tt>Function</tt></a>, if not specified, the BasicBlock must be
  3181. manually inserted into the <a href="#Function"><tt>Function</tt></a>.</p></li>
  3182. <li><tt>BasicBlock::iterator</tt> - Typedef for instruction list iterator<br>
  3183. <tt>BasicBlock::const_iterator</tt> - Typedef for const_iterator.<br>
  3184. <tt>begin()</tt>, <tt>end()</tt>, <tt>front()</tt>, <tt>back()</tt>,
  3185. <tt>size()</tt>, <tt>empty()</tt>
  3186. STL-style functions for accessing the instruction list.
  3187. <p>These methods and typedefs are forwarding functions that have the same
  3188. semantics as the standard library methods of the same names. These methods
  3189. expose the underlying instruction list of a basic block in a way that is easy to
  3190. manipulate. To get the full complement of container operations (including
  3191. operations to update the list), you must use the <tt>getInstList()</tt>
  3192. method.</p></li>
  3193. <li><tt>BasicBlock::InstListType &amp;getInstList()</tt>
  3194. <p>This method is used to get access to the underlying container that actually
  3195. holds the Instructions. This method must be used when there isn't a forwarding
  3196. function in the <tt>BasicBlock</tt> class for the operation that you would like
  3197. to perform. Because there are no forwarding functions for "updating"
  3198. operations, you need to use this if you want to update the contents of a
  3199. <tt>BasicBlock</tt>.</p></li>
  3200. <li><tt><a href="#Function">Function</a> *getParent()</tt>
  3201. <p> Returns a pointer to <a href="#Function"><tt>Function</tt></a> the block is
  3202. embedded into, or a null pointer if it is homeless.</p></li>
  3203. <li><tt><a href="#TerminatorInst">TerminatorInst</a> *getTerminator()</tt>
  3204. <p> Returns a pointer to the terminator instruction that appears at the end of
  3205. the <tt>BasicBlock</tt>. If there is no terminator instruction, or if the last
  3206. instruction in the block is not a terminator, then a null pointer is
  3207. returned.</p></li>
  3208. </ul>
  3209. </div>
  3210. <!-- ======================================================================= -->
  3211. <div class="doc_subsection">
  3212. <a name="Argument">The <tt>Argument</tt> class</a>
  3213. </div>
  3214. <div class="doc_text">
  3215. <p>This subclass of Value defines the interface for incoming formal
  3216. arguments to a function. A Function maintains a list of its formal
  3217. arguments. An argument has a pointer to the parent Function.</p>
  3218. </div>
  3219. <!-- *********************************************************************** -->
  3220. <hr>
  3221. <address>
  3222. <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
  3223. src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
  3224. <a href="http://validator.w3.org/check/referer"><img
  3225. src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Strict"></a>
  3226. <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a> and
  3227. <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
  3228. <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
  3229. Last modified: $Date$
  3230. </address>
  3231. </body>
  3232. </html>