BitcodeWriter.cpp 132 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464
  1. //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Bitcode writer implementation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ValueEnumerator.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/Triple.h"
  17. #include "llvm/Analysis/BlockFrequencyInfo.h"
  18. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  19. #include "llvm/Analysis/BranchProbabilityInfo.h"
  20. #include "llvm/Analysis/LoopInfo.h"
  21. #include "llvm/Bitcode/BitstreamWriter.h"
  22. #include "llvm/Bitcode/LLVMBitCodes.h"
  23. #include "llvm/Bitcode/ReaderWriter.h"
  24. #include "llvm/IR/CallSite.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DebugInfoMetadata.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/InlineAsm.h"
  30. #include "llvm/IR/Instructions.h"
  31. #include "llvm/IR/IntrinsicInst.h"
  32. #include "llvm/IR/LLVMContext.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/Operator.h"
  35. #include "llvm/IR/UseListOrder.h"
  36. #include "llvm/IR/ValueSymbolTable.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Support/ErrorHandling.h"
  39. #include "llvm/Support/MathExtras.h"
  40. #include "llvm/Support/Program.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include "llvm/Support/SHA1.h"
  43. #include <cctype>
  44. #include <map>
  45. using namespace llvm;
  46. /// These are manifest constants used by the bitcode writer. They do not need to
  47. /// be kept in sync with the reader, but need to be consistent within this file.
  48. enum {
  49. // VALUE_SYMTAB_BLOCK abbrev id's.
  50. VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  51. VST_ENTRY_7_ABBREV,
  52. VST_ENTRY_6_ABBREV,
  53. VST_BBENTRY_6_ABBREV,
  54. // CONSTANTS_BLOCK abbrev id's.
  55. CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  56. CONSTANTS_INTEGER_ABBREV,
  57. CONSTANTS_CE_CAST_Abbrev,
  58. CONSTANTS_NULL_Abbrev,
  59. // FUNCTION_BLOCK abbrev id's.
  60. FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  61. FUNCTION_INST_BINOP_ABBREV,
  62. FUNCTION_INST_BINOP_FLAGS_ABBREV,
  63. FUNCTION_INST_CAST_ABBREV,
  64. FUNCTION_INST_RET_VOID_ABBREV,
  65. FUNCTION_INST_RET_VAL_ABBREV,
  66. FUNCTION_INST_UNREACHABLE_ABBREV,
  67. FUNCTION_INST_GEP_ABBREV,
  68. };
  69. static unsigned GetEncodedCastOpcode(unsigned Opcode) {
  70. switch (Opcode) {
  71. default: llvm_unreachable("Unknown cast instruction!");
  72. case Instruction::Trunc : return bitc::CAST_TRUNC;
  73. case Instruction::ZExt : return bitc::CAST_ZEXT;
  74. case Instruction::SExt : return bitc::CAST_SEXT;
  75. case Instruction::FPToUI : return bitc::CAST_FPTOUI;
  76. case Instruction::FPToSI : return bitc::CAST_FPTOSI;
  77. case Instruction::UIToFP : return bitc::CAST_UITOFP;
  78. case Instruction::SIToFP : return bitc::CAST_SITOFP;
  79. case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
  80. case Instruction::FPExt : return bitc::CAST_FPEXT;
  81. case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
  82. case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
  83. case Instruction::BitCast : return bitc::CAST_BITCAST;
  84. case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
  85. }
  86. }
  87. static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
  88. switch (Opcode) {
  89. default: llvm_unreachable("Unknown binary instruction!");
  90. case Instruction::Add:
  91. case Instruction::FAdd: return bitc::BINOP_ADD;
  92. case Instruction::Sub:
  93. case Instruction::FSub: return bitc::BINOP_SUB;
  94. case Instruction::Mul:
  95. case Instruction::FMul: return bitc::BINOP_MUL;
  96. case Instruction::UDiv: return bitc::BINOP_UDIV;
  97. case Instruction::FDiv:
  98. case Instruction::SDiv: return bitc::BINOP_SDIV;
  99. case Instruction::URem: return bitc::BINOP_UREM;
  100. case Instruction::FRem:
  101. case Instruction::SRem: return bitc::BINOP_SREM;
  102. case Instruction::Shl: return bitc::BINOP_SHL;
  103. case Instruction::LShr: return bitc::BINOP_LSHR;
  104. case Instruction::AShr: return bitc::BINOP_ASHR;
  105. case Instruction::And: return bitc::BINOP_AND;
  106. case Instruction::Or: return bitc::BINOP_OR;
  107. case Instruction::Xor: return bitc::BINOP_XOR;
  108. }
  109. }
  110. static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
  111. switch (Op) {
  112. default: llvm_unreachable("Unknown RMW operation!");
  113. case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
  114. case AtomicRMWInst::Add: return bitc::RMW_ADD;
  115. case AtomicRMWInst::Sub: return bitc::RMW_SUB;
  116. case AtomicRMWInst::And: return bitc::RMW_AND;
  117. case AtomicRMWInst::Nand: return bitc::RMW_NAND;
  118. case AtomicRMWInst::Or: return bitc::RMW_OR;
  119. case AtomicRMWInst::Xor: return bitc::RMW_XOR;
  120. case AtomicRMWInst::Max: return bitc::RMW_MAX;
  121. case AtomicRMWInst::Min: return bitc::RMW_MIN;
  122. case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
  123. case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
  124. }
  125. }
  126. static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
  127. switch (Ordering) {
  128. case NotAtomic: return bitc::ORDERING_NOTATOMIC;
  129. case Unordered: return bitc::ORDERING_UNORDERED;
  130. case Monotonic: return bitc::ORDERING_MONOTONIC;
  131. case Acquire: return bitc::ORDERING_ACQUIRE;
  132. case Release: return bitc::ORDERING_RELEASE;
  133. case AcquireRelease: return bitc::ORDERING_ACQREL;
  134. case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
  135. }
  136. llvm_unreachable("Invalid ordering");
  137. }
  138. static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
  139. switch (SynchScope) {
  140. case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
  141. case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
  142. }
  143. llvm_unreachable("Invalid synch scope");
  144. }
  145. static void WriteStringRecord(unsigned Code, StringRef Str,
  146. unsigned AbbrevToUse, BitstreamWriter &Stream) {
  147. SmallVector<unsigned, 64> Vals;
  148. // Code: [strchar x N]
  149. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  150. if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
  151. AbbrevToUse = 0;
  152. Vals.push_back(Str[i]);
  153. }
  154. // Emit the finished record.
  155. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  156. }
  157. static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
  158. switch (Kind) {
  159. case Attribute::Alignment:
  160. return bitc::ATTR_KIND_ALIGNMENT;
  161. case Attribute::AlwaysInline:
  162. return bitc::ATTR_KIND_ALWAYS_INLINE;
  163. case Attribute::ArgMemOnly:
  164. return bitc::ATTR_KIND_ARGMEMONLY;
  165. case Attribute::Builtin:
  166. return bitc::ATTR_KIND_BUILTIN;
  167. case Attribute::ByVal:
  168. return bitc::ATTR_KIND_BY_VAL;
  169. case Attribute::Convergent:
  170. return bitc::ATTR_KIND_CONVERGENT;
  171. case Attribute::InAlloca:
  172. return bitc::ATTR_KIND_IN_ALLOCA;
  173. case Attribute::Cold:
  174. return bitc::ATTR_KIND_COLD;
  175. case Attribute::InaccessibleMemOnly:
  176. return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
  177. case Attribute::InaccessibleMemOrArgMemOnly:
  178. return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
  179. case Attribute::InlineHint:
  180. return bitc::ATTR_KIND_INLINE_HINT;
  181. case Attribute::InReg:
  182. return bitc::ATTR_KIND_IN_REG;
  183. case Attribute::JumpTable:
  184. return bitc::ATTR_KIND_JUMP_TABLE;
  185. case Attribute::MinSize:
  186. return bitc::ATTR_KIND_MIN_SIZE;
  187. case Attribute::Naked:
  188. return bitc::ATTR_KIND_NAKED;
  189. case Attribute::Nest:
  190. return bitc::ATTR_KIND_NEST;
  191. case Attribute::NoAlias:
  192. return bitc::ATTR_KIND_NO_ALIAS;
  193. case Attribute::NoBuiltin:
  194. return bitc::ATTR_KIND_NO_BUILTIN;
  195. case Attribute::NoCapture:
  196. return bitc::ATTR_KIND_NO_CAPTURE;
  197. case Attribute::NoDuplicate:
  198. return bitc::ATTR_KIND_NO_DUPLICATE;
  199. case Attribute::NoImplicitFloat:
  200. return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
  201. case Attribute::NoInline:
  202. return bitc::ATTR_KIND_NO_INLINE;
  203. case Attribute::NoRecurse:
  204. return bitc::ATTR_KIND_NO_RECURSE;
  205. case Attribute::NonLazyBind:
  206. return bitc::ATTR_KIND_NON_LAZY_BIND;
  207. case Attribute::NonNull:
  208. return bitc::ATTR_KIND_NON_NULL;
  209. case Attribute::Dereferenceable:
  210. return bitc::ATTR_KIND_DEREFERENCEABLE;
  211. case Attribute::DereferenceableOrNull:
  212. return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
  213. case Attribute::NoRedZone:
  214. return bitc::ATTR_KIND_NO_RED_ZONE;
  215. case Attribute::NoReturn:
  216. return bitc::ATTR_KIND_NO_RETURN;
  217. case Attribute::NoUnwind:
  218. return bitc::ATTR_KIND_NO_UNWIND;
  219. case Attribute::OptimizeForSize:
  220. return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
  221. case Attribute::OptimizeNone:
  222. return bitc::ATTR_KIND_OPTIMIZE_NONE;
  223. case Attribute::ReadNone:
  224. return bitc::ATTR_KIND_READ_NONE;
  225. case Attribute::ReadOnly:
  226. return bitc::ATTR_KIND_READ_ONLY;
  227. case Attribute::Returned:
  228. return bitc::ATTR_KIND_RETURNED;
  229. case Attribute::ReturnsTwice:
  230. return bitc::ATTR_KIND_RETURNS_TWICE;
  231. case Attribute::SExt:
  232. return bitc::ATTR_KIND_S_EXT;
  233. case Attribute::StackAlignment:
  234. return bitc::ATTR_KIND_STACK_ALIGNMENT;
  235. case Attribute::StackProtect:
  236. return bitc::ATTR_KIND_STACK_PROTECT;
  237. case Attribute::StackProtectReq:
  238. return bitc::ATTR_KIND_STACK_PROTECT_REQ;
  239. case Attribute::StackProtectStrong:
  240. return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
  241. case Attribute::SafeStack:
  242. return bitc::ATTR_KIND_SAFESTACK;
  243. case Attribute::StructRet:
  244. return bitc::ATTR_KIND_STRUCT_RET;
  245. case Attribute::SanitizeAddress:
  246. return bitc::ATTR_KIND_SANITIZE_ADDRESS;
  247. case Attribute::SanitizeThread:
  248. return bitc::ATTR_KIND_SANITIZE_THREAD;
  249. case Attribute::SanitizeMemory:
  250. return bitc::ATTR_KIND_SANITIZE_MEMORY;
  251. case Attribute::SwiftSelf:
  252. return bitc::ATTR_KIND_SWIFT_SELF;
  253. case Attribute::UWTable:
  254. return bitc::ATTR_KIND_UW_TABLE;
  255. case Attribute::ZExt:
  256. return bitc::ATTR_KIND_Z_EXT;
  257. case Attribute::EndAttrKinds:
  258. llvm_unreachable("Can not encode end-attribute kinds marker.");
  259. case Attribute::None:
  260. llvm_unreachable("Can not encode none-attribute.");
  261. }
  262. llvm_unreachable("Trying to encode unknown attribute");
  263. }
  264. static void WriteAttributeGroupTable(const ValueEnumerator &VE,
  265. BitstreamWriter &Stream) {
  266. const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
  267. if (AttrGrps.empty()) return;
  268. Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
  269. SmallVector<uint64_t, 64> Record;
  270. for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
  271. AttributeSet AS = AttrGrps[i];
  272. for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
  273. AttributeSet A = AS.getSlotAttributes(i);
  274. Record.push_back(VE.getAttributeGroupID(A));
  275. Record.push_back(AS.getSlotIndex(i));
  276. for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
  277. I != E; ++I) {
  278. Attribute Attr = *I;
  279. if (Attr.isEnumAttribute()) {
  280. Record.push_back(0);
  281. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  282. } else if (Attr.isIntAttribute()) {
  283. Record.push_back(1);
  284. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  285. Record.push_back(Attr.getValueAsInt());
  286. } else {
  287. StringRef Kind = Attr.getKindAsString();
  288. StringRef Val = Attr.getValueAsString();
  289. Record.push_back(Val.empty() ? 3 : 4);
  290. Record.append(Kind.begin(), Kind.end());
  291. Record.push_back(0);
  292. if (!Val.empty()) {
  293. Record.append(Val.begin(), Val.end());
  294. Record.push_back(0);
  295. }
  296. }
  297. }
  298. Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
  299. Record.clear();
  300. }
  301. }
  302. Stream.ExitBlock();
  303. }
  304. static void WriteAttributeTable(const ValueEnumerator &VE,
  305. BitstreamWriter &Stream) {
  306. const std::vector<AttributeSet> &Attrs = VE.getAttributes();
  307. if (Attrs.empty()) return;
  308. Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
  309. SmallVector<uint64_t, 64> Record;
  310. for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
  311. const AttributeSet &A = Attrs[i];
  312. for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
  313. Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
  314. Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
  315. Record.clear();
  316. }
  317. Stream.ExitBlock();
  318. }
  319. /// WriteTypeTable - Write out the type table for a module.
  320. static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  321. const ValueEnumerator::TypeList &TypeList = VE.getTypes();
  322. Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
  323. SmallVector<uint64_t, 64> TypeVals;
  324. uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
  325. // Abbrev for TYPE_CODE_POINTER.
  326. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  327. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
  328. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  329. Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
  330. unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
  331. // Abbrev for TYPE_CODE_FUNCTION.
  332. Abbv = new BitCodeAbbrev();
  333. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
  334. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
  335. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  336. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  337. unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
  338. // Abbrev for TYPE_CODE_STRUCT_ANON.
  339. Abbv = new BitCodeAbbrev();
  340. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
  341. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  342. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  343. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  344. unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
  345. // Abbrev for TYPE_CODE_STRUCT_NAME.
  346. Abbv = new BitCodeAbbrev();
  347. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
  348. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  349. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  350. unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
  351. // Abbrev for TYPE_CODE_STRUCT_NAMED.
  352. Abbv = new BitCodeAbbrev();
  353. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
  354. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  355. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  356. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  357. unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
  358. // Abbrev for TYPE_CODE_ARRAY.
  359. Abbv = new BitCodeAbbrev();
  360. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
  361. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
  362. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  363. unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
  364. // Emit an entry count so the reader can reserve space.
  365. TypeVals.push_back(TypeList.size());
  366. Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
  367. TypeVals.clear();
  368. // Loop over all of the types, emitting each in turn.
  369. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
  370. Type *T = TypeList[i];
  371. int AbbrevToUse = 0;
  372. unsigned Code = 0;
  373. switch (T->getTypeID()) {
  374. case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
  375. case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
  376. case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
  377. case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
  378. case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
  379. case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
  380. case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
  381. case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
  382. case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
  383. case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
  384. case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
  385. case Type::IntegerTyID:
  386. // INTEGER: [width]
  387. Code = bitc::TYPE_CODE_INTEGER;
  388. TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
  389. break;
  390. case Type::PointerTyID: {
  391. PointerType *PTy = cast<PointerType>(T);
  392. // POINTER: [pointee type, address space]
  393. Code = bitc::TYPE_CODE_POINTER;
  394. TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
  395. unsigned AddressSpace = PTy->getAddressSpace();
  396. TypeVals.push_back(AddressSpace);
  397. if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
  398. break;
  399. }
  400. case Type::FunctionTyID: {
  401. FunctionType *FT = cast<FunctionType>(T);
  402. // FUNCTION: [isvararg, retty, paramty x N]
  403. Code = bitc::TYPE_CODE_FUNCTION;
  404. TypeVals.push_back(FT->isVarArg());
  405. TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
  406. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
  407. TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
  408. AbbrevToUse = FunctionAbbrev;
  409. break;
  410. }
  411. case Type::StructTyID: {
  412. StructType *ST = cast<StructType>(T);
  413. // STRUCT: [ispacked, eltty x N]
  414. TypeVals.push_back(ST->isPacked());
  415. // Output all of the element types.
  416. for (StructType::element_iterator I = ST->element_begin(),
  417. E = ST->element_end(); I != E; ++I)
  418. TypeVals.push_back(VE.getTypeID(*I));
  419. if (ST->isLiteral()) {
  420. Code = bitc::TYPE_CODE_STRUCT_ANON;
  421. AbbrevToUse = StructAnonAbbrev;
  422. } else {
  423. if (ST->isOpaque()) {
  424. Code = bitc::TYPE_CODE_OPAQUE;
  425. } else {
  426. Code = bitc::TYPE_CODE_STRUCT_NAMED;
  427. AbbrevToUse = StructNamedAbbrev;
  428. }
  429. // Emit the name if it is present.
  430. if (!ST->getName().empty())
  431. WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
  432. StructNameAbbrev, Stream);
  433. }
  434. break;
  435. }
  436. case Type::ArrayTyID: {
  437. ArrayType *AT = cast<ArrayType>(T);
  438. // ARRAY: [numelts, eltty]
  439. Code = bitc::TYPE_CODE_ARRAY;
  440. TypeVals.push_back(AT->getNumElements());
  441. TypeVals.push_back(VE.getTypeID(AT->getElementType()));
  442. AbbrevToUse = ArrayAbbrev;
  443. break;
  444. }
  445. case Type::VectorTyID: {
  446. VectorType *VT = cast<VectorType>(T);
  447. // VECTOR [numelts, eltty]
  448. Code = bitc::TYPE_CODE_VECTOR;
  449. TypeVals.push_back(VT->getNumElements());
  450. TypeVals.push_back(VE.getTypeID(VT->getElementType()));
  451. break;
  452. }
  453. }
  454. // Emit the finished record.
  455. Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
  456. TypeVals.clear();
  457. }
  458. Stream.ExitBlock();
  459. }
  460. static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
  461. switch (Linkage) {
  462. case GlobalValue::ExternalLinkage:
  463. return 0;
  464. case GlobalValue::WeakAnyLinkage:
  465. return 16;
  466. case GlobalValue::AppendingLinkage:
  467. return 2;
  468. case GlobalValue::InternalLinkage:
  469. return 3;
  470. case GlobalValue::LinkOnceAnyLinkage:
  471. return 18;
  472. case GlobalValue::ExternalWeakLinkage:
  473. return 7;
  474. case GlobalValue::CommonLinkage:
  475. return 8;
  476. case GlobalValue::PrivateLinkage:
  477. return 9;
  478. case GlobalValue::WeakODRLinkage:
  479. return 17;
  480. case GlobalValue::LinkOnceODRLinkage:
  481. return 19;
  482. case GlobalValue::AvailableExternallyLinkage:
  483. return 12;
  484. }
  485. llvm_unreachable("Invalid linkage");
  486. }
  487. static unsigned getEncodedLinkage(const GlobalValue &GV) {
  488. return getEncodedLinkage(GV.getLinkage());
  489. }
  490. static unsigned getEncodedVisibility(const GlobalValue &GV) {
  491. switch (GV.getVisibility()) {
  492. case GlobalValue::DefaultVisibility: return 0;
  493. case GlobalValue::HiddenVisibility: return 1;
  494. case GlobalValue::ProtectedVisibility: return 2;
  495. }
  496. llvm_unreachable("Invalid visibility");
  497. }
  498. static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
  499. switch (GV.getDLLStorageClass()) {
  500. case GlobalValue::DefaultStorageClass: return 0;
  501. case GlobalValue::DLLImportStorageClass: return 1;
  502. case GlobalValue::DLLExportStorageClass: return 2;
  503. }
  504. llvm_unreachable("Invalid DLL storage class");
  505. }
  506. static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
  507. switch (GV.getThreadLocalMode()) {
  508. case GlobalVariable::NotThreadLocal: return 0;
  509. case GlobalVariable::GeneralDynamicTLSModel: return 1;
  510. case GlobalVariable::LocalDynamicTLSModel: return 2;
  511. case GlobalVariable::InitialExecTLSModel: return 3;
  512. case GlobalVariable::LocalExecTLSModel: return 4;
  513. }
  514. llvm_unreachable("Invalid TLS model");
  515. }
  516. static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
  517. switch (C.getSelectionKind()) {
  518. case Comdat::Any:
  519. return bitc::COMDAT_SELECTION_KIND_ANY;
  520. case Comdat::ExactMatch:
  521. return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
  522. case Comdat::Largest:
  523. return bitc::COMDAT_SELECTION_KIND_LARGEST;
  524. case Comdat::NoDuplicates:
  525. return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
  526. case Comdat::SameSize:
  527. return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
  528. }
  529. llvm_unreachable("Invalid selection kind");
  530. }
  531. static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  532. SmallVector<unsigned, 64> Vals;
  533. for (const Comdat *C : VE.getComdats()) {
  534. // COMDAT: [selection_kind, name]
  535. Vals.push_back(getEncodedComdatSelectionKind(*C));
  536. size_t Size = C->getName().size();
  537. assert(isUInt<32>(Size));
  538. Vals.push_back(Size);
  539. for (char Chr : C->getName())
  540. Vals.push_back((unsigned char)Chr);
  541. Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
  542. Vals.clear();
  543. }
  544. }
  545. /// Write a record that will eventually hold the word offset of the
  546. /// module-level VST. For now the offset is 0, which will be backpatched
  547. /// after the real VST is written. Returns the bit offset to backpatch.
  548. static uint64_t WriteValueSymbolTableForwardDecl(BitstreamWriter &Stream) {
  549. // Write a placeholder value in for the offset of the real VST,
  550. // which is written after the function blocks so that it can include
  551. // the offset of each function. The placeholder offset will be
  552. // updated when the real VST is written.
  553. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  554. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
  555. // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
  556. // hold the real VST offset. Must use fixed instead of VBR as we don't
  557. // know how many VBR chunks to reserve ahead of time.
  558. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  559. unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
  560. // Emit the placeholder
  561. uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
  562. Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
  563. // Compute and return the bit offset to the placeholder, which will be
  564. // patched when the real VST is written. We can simply subtract the 32-bit
  565. // fixed size from the current bit number to get the location to backpatch.
  566. return Stream.GetCurrentBitNo() - 32;
  567. }
  568. enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
  569. /// Determine the encoding to use for the given string name and length.
  570. static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
  571. bool isChar6 = true;
  572. for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
  573. if (isChar6)
  574. isChar6 = BitCodeAbbrevOp::isChar6(*C);
  575. if ((unsigned char)*C & 128)
  576. // don't bother scanning the rest.
  577. return SE_Fixed8;
  578. }
  579. if (isChar6)
  580. return SE_Char6;
  581. else
  582. return SE_Fixed7;
  583. }
  584. /// Emit top-level description of module, including target triple, inline asm,
  585. /// descriptors for global variables, and function prototype info.
  586. /// Returns the bit offset to backpatch with the location of the real VST.
  587. static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
  588. BitstreamWriter &Stream) {
  589. // Emit various pieces of data attached to a module.
  590. if (!M->getTargetTriple().empty())
  591. WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
  592. 0/*TODO*/, Stream);
  593. const std::string &DL = M->getDataLayoutStr();
  594. if (!DL.empty())
  595. WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
  596. if (!M->getModuleInlineAsm().empty())
  597. WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
  598. 0/*TODO*/, Stream);
  599. // Emit information about sections and GC, computing how many there are. Also
  600. // compute the maximum alignment value.
  601. std::map<std::string, unsigned> SectionMap;
  602. std::map<std::string, unsigned> GCMap;
  603. unsigned MaxAlignment = 0;
  604. unsigned MaxGlobalType = 0;
  605. for (const GlobalValue &GV : M->globals()) {
  606. MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
  607. MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
  608. if (GV.hasSection()) {
  609. // Give section names unique ID's.
  610. unsigned &Entry = SectionMap[GV.getSection()];
  611. if (!Entry) {
  612. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
  613. 0/*TODO*/, Stream);
  614. Entry = SectionMap.size();
  615. }
  616. }
  617. }
  618. for (const Function &F : *M) {
  619. MaxAlignment = std::max(MaxAlignment, F.getAlignment());
  620. if (F.hasSection()) {
  621. // Give section names unique ID's.
  622. unsigned &Entry = SectionMap[F.getSection()];
  623. if (!Entry) {
  624. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
  625. 0/*TODO*/, Stream);
  626. Entry = SectionMap.size();
  627. }
  628. }
  629. if (F.hasGC()) {
  630. // Same for GC names.
  631. unsigned &Entry = GCMap[F.getGC()];
  632. if (!Entry) {
  633. WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
  634. 0/*TODO*/, Stream);
  635. Entry = GCMap.size();
  636. }
  637. }
  638. }
  639. // Emit abbrev for globals, now that we know # sections and max alignment.
  640. unsigned SimpleGVarAbbrev = 0;
  641. if (!M->global_empty()) {
  642. // Add an abbrev for common globals with no visibility or thread localness.
  643. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  644. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
  645. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  646. Log2_32_Ceil(MaxGlobalType+1)));
  647. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
  648. //| explicitType << 1
  649. //| constant
  650. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
  651. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
  652. if (MaxAlignment == 0) // Alignment.
  653. Abbv->Add(BitCodeAbbrevOp(0));
  654. else {
  655. unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
  656. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  657. Log2_32_Ceil(MaxEncAlignment+1)));
  658. }
  659. if (SectionMap.empty()) // Section.
  660. Abbv->Add(BitCodeAbbrevOp(0));
  661. else
  662. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  663. Log2_32_Ceil(SectionMap.size()+1)));
  664. // Don't bother emitting vis + thread local.
  665. SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
  666. }
  667. // Emit the global variable information.
  668. SmallVector<unsigned, 64> Vals;
  669. for (const GlobalVariable &GV : M->globals()) {
  670. unsigned AbbrevToUse = 0;
  671. // GLOBALVAR: [type, isconst, initid,
  672. // linkage, alignment, section, visibility, threadlocal,
  673. // unnamed_addr, externally_initialized, dllstorageclass,
  674. // comdat]
  675. Vals.push_back(VE.getTypeID(GV.getValueType()));
  676. Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
  677. Vals.push_back(GV.isDeclaration() ? 0 :
  678. (VE.getValueID(GV.getInitializer()) + 1));
  679. Vals.push_back(getEncodedLinkage(GV));
  680. Vals.push_back(Log2_32(GV.getAlignment())+1);
  681. Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
  682. if (GV.isThreadLocal() ||
  683. GV.getVisibility() != GlobalValue::DefaultVisibility ||
  684. GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
  685. GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
  686. GV.hasComdat()) {
  687. Vals.push_back(getEncodedVisibility(GV));
  688. Vals.push_back(getEncodedThreadLocalMode(GV));
  689. Vals.push_back(GV.hasUnnamedAddr());
  690. Vals.push_back(GV.isExternallyInitialized());
  691. Vals.push_back(getEncodedDLLStorageClass(GV));
  692. Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
  693. } else {
  694. AbbrevToUse = SimpleGVarAbbrev;
  695. }
  696. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
  697. Vals.clear();
  698. }
  699. // Emit the function proto information.
  700. for (const Function &F : *M) {
  701. // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
  702. // section, visibility, gc, unnamed_addr, prologuedata,
  703. // dllstorageclass, comdat, prefixdata, personalityfn]
  704. Vals.push_back(VE.getTypeID(F.getFunctionType()));
  705. Vals.push_back(F.getCallingConv());
  706. Vals.push_back(F.isDeclaration());
  707. Vals.push_back(getEncodedLinkage(F));
  708. Vals.push_back(VE.getAttributeID(F.getAttributes()));
  709. Vals.push_back(Log2_32(F.getAlignment())+1);
  710. Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
  711. Vals.push_back(getEncodedVisibility(F));
  712. Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
  713. Vals.push_back(F.hasUnnamedAddr());
  714. Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
  715. : 0);
  716. Vals.push_back(getEncodedDLLStorageClass(F));
  717. Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
  718. Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
  719. : 0);
  720. Vals.push_back(
  721. F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
  722. unsigned AbbrevToUse = 0;
  723. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
  724. Vals.clear();
  725. }
  726. // Emit the alias information.
  727. for (const GlobalAlias &A : M->aliases()) {
  728. // ALIAS: [alias type, aliasee val#, linkage, visibility]
  729. Vals.push_back(VE.getTypeID(A.getValueType()));
  730. Vals.push_back(A.getType()->getAddressSpace());
  731. Vals.push_back(VE.getValueID(A.getAliasee()));
  732. Vals.push_back(getEncodedLinkage(A));
  733. Vals.push_back(getEncodedVisibility(A));
  734. Vals.push_back(getEncodedDLLStorageClass(A));
  735. Vals.push_back(getEncodedThreadLocalMode(A));
  736. Vals.push_back(A.hasUnnamedAddr());
  737. unsigned AbbrevToUse = 0;
  738. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
  739. Vals.clear();
  740. }
  741. // Emit the module's source file name.
  742. {
  743. StringEncoding Bits = getStringEncoding(M->getSourceFileName().data(),
  744. M->getSourceFileName().size());
  745. BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
  746. if (Bits == SE_Char6)
  747. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
  748. else if (Bits == SE_Fixed7)
  749. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
  750. // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  751. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  752. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
  753. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  754. Abbv->Add(AbbrevOpToUse);
  755. unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv);
  756. for (const auto P : M->getSourceFileName())
  757. Vals.push_back((unsigned char)P);
  758. // Emit the finished record.
  759. Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
  760. Vals.clear();
  761. }
  762. // If we have a VST, write the VSTOFFSET record placeholder and return
  763. // its offset.
  764. if (M->getValueSymbolTable().empty())
  765. return 0;
  766. return WriteValueSymbolTableForwardDecl(Stream);
  767. }
  768. static uint64_t GetOptimizationFlags(const Value *V) {
  769. uint64_t Flags = 0;
  770. if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
  771. if (OBO->hasNoSignedWrap())
  772. Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
  773. if (OBO->hasNoUnsignedWrap())
  774. Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
  775. } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
  776. if (PEO->isExact())
  777. Flags |= 1 << bitc::PEO_EXACT;
  778. } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
  779. if (FPMO->hasUnsafeAlgebra())
  780. Flags |= FastMathFlags::UnsafeAlgebra;
  781. if (FPMO->hasNoNaNs())
  782. Flags |= FastMathFlags::NoNaNs;
  783. if (FPMO->hasNoInfs())
  784. Flags |= FastMathFlags::NoInfs;
  785. if (FPMO->hasNoSignedZeros())
  786. Flags |= FastMathFlags::NoSignedZeros;
  787. if (FPMO->hasAllowReciprocal())
  788. Flags |= FastMathFlags::AllowReciprocal;
  789. }
  790. return Flags;
  791. }
  792. static void writeValueAsMetadata(const ValueAsMetadata *MD,
  793. const ValueEnumerator &VE,
  794. BitstreamWriter &Stream,
  795. SmallVectorImpl<uint64_t> &Record) {
  796. // Mimic an MDNode with a value as one operand.
  797. Value *V = MD->getValue();
  798. Record.push_back(VE.getTypeID(V->getType()));
  799. Record.push_back(VE.getValueID(V));
  800. Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
  801. Record.clear();
  802. }
  803. static void writeMDTuple(const MDTuple *N, const ValueEnumerator &VE,
  804. BitstreamWriter &Stream,
  805. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
  806. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  807. Metadata *MD = N->getOperand(i);
  808. assert(!(MD && isa<LocalAsMetadata>(MD)) &&
  809. "Unexpected function-local metadata");
  810. Record.push_back(VE.getMetadataOrNullID(MD));
  811. }
  812. Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
  813. : bitc::METADATA_NODE,
  814. Record, Abbrev);
  815. Record.clear();
  816. }
  817. static unsigned createDILocationAbbrev(BitstreamWriter &Stream) {
  818. // Assume the column is usually under 128, and always output the inlined-at
  819. // location (it's never more expensive than building an array size 1).
  820. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  821. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
  822. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  823. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  824. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  825. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  826. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  827. return Stream.EmitAbbrev(Abbv);
  828. }
  829. static void writeDILocation(const DILocation *N, const ValueEnumerator &VE,
  830. BitstreamWriter &Stream,
  831. SmallVectorImpl<uint64_t> &Record,
  832. unsigned &Abbrev) {
  833. if (!Abbrev)
  834. Abbrev = createDILocationAbbrev(Stream);
  835. Record.push_back(N->isDistinct());
  836. Record.push_back(N->getLine());
  837. Record.push_back(N->getColumn());
  838. Record.push_back(VE.getMetadataID(N->getScope()));
  839. Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
  840. Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
  841. Record.clear();
  842. }
  843. static unsigned createGenericDINodeAbbrev(BitstreamWriter &Stream) {
  844. // Assume the column is usually under 128, and always output the inlined-at
  845. // location (it's never more expensive than building an array size 1).
  846. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  847. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
  848. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  849. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  850. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  851. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  852. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  853. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  854. return Stream.EmitAbbrev(Abbv);
  855. }
  856. static void writeGenericDINode(const GenericDINode *N,
  857. const ValueEnumerator &VE,
  858. BitstreamWriter &Stream,
  859. SmallVectorImpl<uint64_t> &Record,
  860. unsigned &Abbrev) {
  861. if (!Abbrev)
  862. Abbrev = createGenericDINodeAbbrev(Stream);
  863. Record.push_back(N->isDistinct());
  864. Record.push_back(N->getTag());
  865. Record.push_back(0); // Per-tag version field; unused for now.
  866. for (auto &I : N->operands())
  867. Record.push_back(VE.getMetadataOrNullID(I));
  868. Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
  869. Record.clear();
  870. }
  871. static uint64_t rotateSign(int64_t I) {
  872. uint64_t U = I;
  873. return I < 0 ? ~(U << 1) : U << 1;
  874. }
  875. static void writeDISubrange(const DISubrange *N, const ValueEnumerator &,
  876. BitstreamWriter &Stream,
  877. SmallVectorImpl<uint64_t> &Record,
  878. unsigned Abbrev) {
  879. Record.push_back(N->isDistinct());
  880. Record.push_back(N->getCount());
  881. Record.push_back(rotateSign(N->getLowerBound()));
  882. Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
  883. Record.clear();
  884. }
  885. static void writeDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
  886. BitstreamWriter &Stream,
  887. SmallVectorImpl<uint64_t> &Record,
  888. unsigned Abbrev) {
  889. Record.push_back(N->isDistinct());
  890. Record.push_back(rotateSign(N->getValue()));
  891. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  892. Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
  893. Record.clear();
  894. }
  895. static void writeDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
  896. BitstreamWriter &Stream,
  897. SmallVectorImpl<uint64_t> &Record,
  898. unsigned Abbrev) {
  899. Record.push_back(N->isDistinct());
  900. Record.push_back(N->getTag());
  901. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  902. Record.push_back(N->getSizeInBits());
  903. Record.push_back(N->getAlignInBits());
  904. Record.push_back(N->getEncoding());
  905. Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
  906. Record.clear();
  907. }
  908. static void writeDIDerivedType(const DIDerivedType *N,
  909. const ValueEnumerator &VE,
  910. BitstreamWriter &Stream,
  911. SmallVectorImpl<uint64_t> &Record,
  912. unsigned Abbrev) {
  913. Record.push_back(N->isDistinct());
  914. Record.push_back(N->getTag());
  915. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  916. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  917. Record.push_back(N->getLine());
  918. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  919. Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
  920. Record.push_back(N->getSizeInBits());
  921. Record.push_back(N->getAlignInBits());
  922. Record.push_back(N->getOffsetInBits());
  923. Record.push_back(N->getFlags());
  924. Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
  925. Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
  926. Record.clear();
  927. }
  928. static void writeDICompositeType(const DICompositeType *N,
  929. const ValueEnumerator &VE,
  930. BitstreamWriter &Stream,
  931. SmallVectorImpl<uint64_t> &Record,
  932. unsigned Abbrev) {
  933. Record.push_back(N->isDistinct());
  934. Record.push_back(N->getTag());
  935. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  936. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  937. Record.push_back(N->getLine());
  938. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  939. Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
  940. Record.push_back(N->getSizeInBits());
  941. Record.push_back(N->getAlignInBits());
  942. Record.push_back(N->getOffsetInBits());
  943. Record.push_back(N->getFlags());
  944. Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
  945. Record.push_back(N->getRuntimeLang());
  946. Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
  947. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
  948. Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
  949. Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
  950. Record.clear();
  951. }
  952. static void writeDISubroutineType(const DISubroutineType *N,
  953. const ValueEnumerator &VE,
  954. BitstreamWriter &Stream,
  955. SmallVectorImpl<uint64_t> &Record,
  956. unsigned Abbrev) {
  957. Record.push_back(N->isDistinct());
  958. Record.push_back(N->getFlags());
  959. Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
  960. Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
  961. Record.clear();
  962. }
  963. static void writeDIFile(const DIFile *N, const ValueEnumerator &VE,
  964. BitstreamWriter &Stream,
  965. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
  966. Record.push_back(N->isDistinct());
  967. Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
  968. Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
  969. Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
  970. Record.clear();
  971. }
  972. static void writeDICompileUnit(const DICompileUnit *N,
  973. const ValueEnumerator &VE,
  974. BitstreamWriter &Stream,
  975. SmallVectorImpl<uint64_t> &Record,
  976. unsigned Abbrev) {
  977. assert(N->isDistinct() && "Expected distinct compile units");
  978. Record.push_back(/* IsDistinct */ true);
  979. Record.push_back(N->getSourceLanguage());
  980. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  981. Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
  982. Record.push_back(N->isOptimized());
  983. Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
  984. Record.push_back(N->getRuntimeVersion());
  985. Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
  986. Record.push_back(N->getEmissionKind());
  987. Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
  988. Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
  989. Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
  990. Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
  991. Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
  992. Record.push_back(N->getDWOId());
  993. Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
  994. Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
  995. Record.clear();
  996. }
  997. static void writeDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
  998. BitstreamWriter &Stream,
  999. SmallVectorImpl<uint64_t> &Record,
  1000. unsigned Abbrev) {
  1001. Record.push_back(N->isDistinct());
  1002. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1003. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1004. Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
  1005. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1006. Record.push_back(N->getLine());
  1007. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1008. Record.push_back(N->isLocalToUnit());
  1009. Record.push_back(N->isDefinition());
  1010. Record.push_back(N->getScopeLine());
  1011. Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
  1012. Record.push_back(N->getVirtuality());
  1013. Record.push_back(N->getVirtualIndex());
  1014. Record.push_back(N->getFlags());
  1015. Record.push_back(N->isOptimized());
  1016. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
  1017. Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
  1018. Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
  1019. Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
  1020. Record.clear();
  1021. }
  1022. static void writeDILexicalBlock(const DILexicalBlock *N,
  1023. const ValueEnumerator &VE,
  1024. BitstreamWriter &Stream,
  1025. SmallVectorImpl<uint64_t> &Record,
  1026. unsigned Abbrev) {
  1027. Record.push_back(N->isDistinct());
  1028. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1029. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1030. Record.push_back(N->getLine());
  1031. Record.push_back(N->getColumn());
  1032. Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
  1033. Record.clear();
  1034. }
  1035. static void writeDILexicalBlockFile(const DILexicalBlockFile *N,
  1036. const ValueEnumerator &VE,
  1037. BitstreamWriter &Stream,
  1038. SmallVectorImpl<uint64_t> &Record,
  1039. unsigned Abbrev) {
  1040. Record.push_back(N->isDistinct());
  1041. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1042. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1043. Record.push_back(N->getDiscriminator());
  1044. Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
  1045. Record.clear();
  1046. }
  1047. static void writeDINamespace(const DINamespace *N, const ValueEnumerator &VE,
  1048. BitstreamWriter &Stream,
  1049. SmallVectorImpl<uint64_t> &Record,
  1050. unsigned Abbrev) {
  1051. Record.push_back(N->isDistinct());
  1052. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1053. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1054. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1055. Record.push_back(N->getLine());
  1056. Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
  1057. Record.clear();
  1058. }
  1059. static void writeDIMacro(const DIMacro *N, const ValueEnumerator &VE,
  1060. BitstreamWriter &Stream,
  1061. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
  1062. Record.push_back(N->isDistinct());
  1063. Record.push_back(N->getMacinfoType());
  1064. Record.push_back(N->getLine());
  1065. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1066. Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
  1067. Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
  1068. Record.clear();
  1069. }
  1070. static void writeDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE,
  1071. BitstreamWriter &Stream,
  1072. SmallVectorImpl<uint64_t> &Record,
  1073. unsigned Abbrev) {
  1074. Record.push_back(N->isDistinct());
  1075. Record.push_back(N->getMacinfoType());
  1076. Record.push_back(N->getLine());
  1077. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1078. Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
  1079. Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
  1080. Record.clear();
  1081. }
  1082. static void writeDIModule(const DIModule *N, const ValueEnumerator &VE,
  1083. BitstreamWriter &Stream,
  1084. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
  1085. Record.push_back(N->isDistinct());
  1086. for (auto &I : N->operands())
  1087. Record.push_back(VE.getMetadataOrNullID(I));
  1088. Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
  1089. Record.clear();
  1090. }
  1091. static void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
  1092. const ValueEnumerator &VE,
  1093. BitstreamWriter &Stream,
  1094. SmallVectorImpl<uint64_t> &Record,
  1095. unsigned Abbrev) {
  1096. Record.push_back(N->isDistinct());
  1097. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1098. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1099. Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
  1100. Record.clear();
  1101. }
  1102. static void writeDITemplateValueParameter(const DITemplateValueParameter *N,
  1103. const ValueEnumerator &VE,
  1104. BitstreamWriter &Stream,
  1105. SmallVectorImpl<uint64_t> &Record,
  1106. unsigned Abbrev) {
  1107. Record.push_back(N->isDistinct());
  1108. Record.push_back(N->getTag());
  1109. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1110. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1111. Record.push_back(VE.getMetadataOrNullID(N->getValue()));
  1112. Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
  1113. Record.clear();
  1114. }
  1115. static void writeDIGlobalVariable(const DIGlobalVariable *N,
  1116. const ValueEnumerator &VE,
  1117. BitstreamWriter &Stream,
  1118. SmallVectorImpl<uint64_t> &Record,
  1119. unsigned Abbrev) {
  1120. Record.push_back(N->isDistinct());
  1121. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1122. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1123. Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
  1124. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1125. Record.push_back(N->getLine());
  1126. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1127. Record.push_back(N->isLocalToUnit());
  1128. Record.push_back(N->isDefinition());
  1129. Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
  1130. Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
  1131. Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
  1132. Record.clear();
  1133. }
  1134. static void writeDILocalVariable(const DILocalVariable *N,
  1135. const ValueEnumerator &VE,
  1136. BitstreamWriter &Stream,
  1137. SmallVectorImpl<uint64_t> &Record,
  1138. unsigned Abbrev) {
  1139. Record.push_back(N->isDistinct());
  1140. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1141. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1142. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1143. Record.push_back(N->getLine());
  1144. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1145. Record.push_back(N->getArg());
  1146. Record.push_back(N->getFlags());
  1147. Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
  1148. Record.clear();
  1149. }
  1150. static void writeDIExpression(const DIExpression *N, const ValueEnumerator &,
  1151. BitstreamWriter &Stream,
  1152. SmallVectorImpl<uint64_t> &Record,
  1153. unsigned Abbrev) {
  1154. Record.reserve(N->getElements().size() + 1);
  1155. Record.push_back(N->isDistinct());
  1156. Record.append(N->elements_begin(), N->elements_end());
  1157. Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
  1158. Record.clear();
  1159. }
  1160. static void writeDIObjCProperty(const DIObjCProperty *N,
  1161. const ValueEnumerator &VE,
  1162. BitstreamWriter &Stream,
  1163. SmallVectorImpl<uint64_t> &Record,
  1164. unsigned Abbrev) {
  1165. Record.push_back(N->isDistinct());
  1166. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1167. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1168. Record.push_back(N->getLine());
  1169. Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
  1170. Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
  1171. Record.push_back(N->getAttributes());
  1172. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1173. Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
  1174. Record.clear();
  1175. }
  1176. static void writeDIImportedEntity(const DIImportedEntity *N,
  1177. const ValueEnumerator &VE,
  1178. BitstreamWriter &Stream,
  1179. SmallVectorImpl<uint64_t> &Record,
  1180. unsigned Abbrev) {
  1181. Record.push_back(N->isDistinct());
  1182. Record.push_back(N->getTag());
  1183. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1184. Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
  1185. Record.push_back(N->getLine());
  1186. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1187. Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
  1188. Record.clear();
  1189. }
  1190. static unsigned createNamedMetadataAbbrev(BitstreamWriter &Stream) {
  1191. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1192. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
  1193. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1194. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1195. return Stream.EmitAbbrev(Abbv);
  1196. }
  1197. static void writeNamedMetadata(const Module &M, const ValueEnumerator &VE,
  1198. BitstreamWriter &Stream,
  1199. SmallVectorImpl<uint64_t> &Record) {
  1200. if (M.named_metadata_empty())
  1201. return;
  1202. unsigned Abbrev = createNamedMetadataAbbrev(Stream);
  1203. for (const NamedMDNode &NMD : M.named_metadata()) {
  1204. // Write name.
  1205. StringRef Str = NMD.getName();
  1206. Record.append(Str.bytes_begin(), Str.bytes_end());
  1207. Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
  1208. Record.clear();
  1209. // Write named metadata operands.
  1210. for (const MDNode *N : NMD.operands())
  1211. Record.push_back(VE.getMetadataID(N));
  1212. Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
  1213. Record.clear();
  1214. }
  1215. }
  1216. static unsigned createMetadataStringsAbbrev(BitstreamWriter &Stream) {
  1217. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1218. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
  1219. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
  1220. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
  1221. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1222. return Stream.EmitAbbrev(Abbv);
  1223. }
  1224. /// Write out a record for MDString.
  1225. ///
  1226. /// All the metadata strings in a metadata block are emitted in a single
  1227. /// record. The sizes and strings themselves are shoved into a blob.
  1228. static void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
  1229. BitstreamWriter &Stream,
  1230. SmallVectorImpl<uint64_t> &Record) {
  1231. if (Strings.empty())
  1232. return;
  1233. // Start the record with the number of strings.
  1234. Record.push_back(bitc::METADATA_STRINGS);
  1235. Record.push_back(Strings.size());
  1236. // Emit the sizes of the strings in the blob.
  1237. SmallString<256> Blob;
  1238. {
  1239. BitstreamWriter W(Blob);
  1240. for (const Metadata *MD : Strings)
  1241. W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
  1242. W.FlushToWord();
  1243. }
  1244. // Add the offset to the strings to the record.
  1245. Record.push_back(Blob.size());
  1246. // Add the strings to the blob.
  1247. for (const Metadata *MD : Strings)
  1248. Blob.append(cast<MDString>(MD)->getString());
  1249. // Emit the final record.
  1250. Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(Stream), Record, Blob);
  1251. Record.clear();
  1252. }
  1253. static void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
  1254. const ValueEnumerator &VE,
  1255. BitstreamWriter &Stream,
  1256. SmallVectorImpl<uint64_t> &Record) {
  1257. if (MDs.empty())
  1258. return;
  1259. // Initialize MDNode abbreviations.
  1260. #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
  1261. #include "llvm/IR/Metadata.def"
  1262. for (const Metadata *MD : MDs) {
  1263. if (const MDNode *N = dyn_cast<MDNode>(MD)) {
  1264. assert(N->isResolved() && "Expected forward references to be resolved");
  1265. switch (N->getMetadataID()) {
  1266. default:
  1267. llvm_unreachable("Invalid MDNode subclass");
  1268. #define HANDLE_MDNODE_LEAF(CLASS) \
  1269. case Metadata::CLASS##Kind: \
  1270. write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
  1271. continue;
  1272. #include "llvm/IR/Metadata.def"
  1273. }
  1274. }
  1275. writeValueAsMetadata(cast<ValueAsMetadata>(MD), VE, Stream, Record);
  1276. }
  1277. }
  1278. static void writeModuleMetadata(const Module &M,
  1279. const ValueEnumerator &VE,
  1280. BitstreamWriter &Stream) {
  1281. if (VE.getMDs().empty() && M.named_metadata_empty())
  1282. return;
  1283. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  1284. SmallVector<uint64_t, 64> Record;
  1285. writeMetadataStrings(VE.getMDStrings(), Stream, Record);
  1286. writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record);
  1287. writeNamedMetadata(M, VE, Stream, Record);
  1288. Stream.ExitBlock();
  1289. }
  1290. static void writeFunctionMetadata(const Function &F, const ValueEnumerator &VE,
  1291. BitstreamWriter &Stream) {
  1292. ArrayRef<const Metadata *> MDs = VE.getFunctionMDs();
  1293. if (MDs.empty())
  1294. return;
  1295. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  1296. SmallVector<uint64_t, 64> Record;
  1297. writeMetadataRecords(MDs, VE, Stream, Record);
  1298. Stream.ExitBlock();
  1299. }
  1300. static void WriteMetadataAttachment(const Function &F,
  1301. const ValueEnumerator &VE,
  1302. BitstreamWriter &Stream) {
  1303. Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
  1304. SmallVector<uint64_t, 64> Record;
  1305. // Write metadata attachments
  1306. // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
  1307. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  1308. F.getAllMetadata(MDs);
  1309. if (!MDs.empty()) {
  1310. for (const auto &I : MDs) {
  1311. Record.push_back(I.first);
  1312. Record.push_back(VE.getMetadataID(I.second));
  1313. }
  1314. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  1315. Record.clear();
  1316. }
  1317. for (const BasicBlock &BB : F)
  1318. for (const Instruction &I : BB) {
  1319. MDs.clear();
  1320. I.getAllMetadataOtherThanDebugLoc(MDs);
  1321. // If no metadata, ignore instruction.
  1322. if (MDs.empty()) continue;
  1323. Record.push_back(VE.getInstructionID(&I));
  1324. for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
  1325. Record.push_back(MDs[i].first);
  1326. Record.push_back(VE.getMetadataID(MDs[i].second));
  1327. }
  1328. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  1329. Record.clear();
  1330. }
  1331. Stream.ExitBlock();
  1332. }
  1333. static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
  1334. SmallVector<uint64_t, 64> Record;
  1335. // Write metadata kinds
  1336. // METADATA_KIND - [n x [id, name]]
  1337. SmallVector<StringRef, 8> Names;
  1338. M->getMDKindNames(Names);
  1339. if (Names.empty()) return;
  1340. Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
  1341. for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
  1342. Record.push_back(MDKindID);
  1343. StringRef KName = Names[MDKindID];
  1344. Record.append(KName.begin(), KName.end());
  1345. Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
  1346. Record.clear();
  1347. }
  1348. Stream.ExitBlock();
  1349. }
  1350. static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
  1351. // Write metadata kinds
  1352. //
  1353. // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
  1354. //
  1355. // OPERAND_BUNDLE_TAG - [strchr x N]
  1356. SmallVector<StringRef, 8> Tags;
  1357. M->getOperandBundleTags(Tags);
  1358. if (Tags.empty())
  1359. return;
  1360. Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
  1361. SmallVector<uint64_t, 64> Record;
  1362. for (auto Tag : Tags) {
  1363. Record.append(Tag.begin(), Tag.end());
  1364. Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
  1365. Record.clear();
  1366. }
  1367. Stream.ExitBlock();
  1368. }
  1369. static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
  1370. if ((int64_t)V >= 0)
  1371. Vals.push_back(V << 1);
  1372. else
  1373. Vals.push_back((-V << 1) | 1);
  1374. }
  1375. static void WriteConstants(unsigned FirstVal, unsigned LastVal,
  1376. const ValueEnumerator &VE,
  1377. BitstreamWriter &Stream, bool isGlobal) {
  1378. if (FirstVal == LastVal) return;
  1379. Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
  1380. unsigned AggregateAbbrev = 0;
  1381. unsigned String8Abbrev = 0;
  1382. unsigned CString7Abbrev = 0;
  1383. unsigned CString6Abbrev = 0;
  1384. // If this is a constant pool for the module, emit module-specific abbrevs.
  1385. if (isGlobal) {
  1386. // Abbrev for CST_CODE_AGGREGATE.
  1387. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1388. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
  1389. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1390. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
  1391. AggregateAbbrev = Stream.EmitAbbrev(Abbv);
  1392. // Abbrev for CST_CODE_STRING.
  1393. Abbv = new BitCodeAbbrev();
  1394. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
  1395. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1396. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1397. String8Abbrev = Stream.EmitAbbrev(Abbv);
  1398. // Abbrev for CST_CODE_CSTRING.
  1399. Abbv = new BitCodeAbbrev();
  1400. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  1401. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1402. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  1403. CString7Abbrev = Stream.EmitAbbrev(Abbv);
  1404. // Abbrev for CST_CODE_CSTRING.
  1405. Abbv = new BitCodeAbbrev();
  1406. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  1407. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1408. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  1409. CString6Abbrev = Stream.EmitAbbrev(Abbv);
  1410. }
  1411. SmallVector<uint64_t, 64> Record;
  1412. const ValueEnumerator::ValueList &Vals = VE.getValues();
  1413. Type *LastTy = nullptr;
  1414. for (unsigned i = FirstVal; i != LastVal; ++i) {
  1415. const Value *V = Vals[i].first;
  1416. // If we need to switch types, do so now.
  1417. if (V->getType() != LastTy) {
  1418. LastTy = V->getType();
  1419. Record.push_back(VE.getTypeID(LastTy));
  1420. Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
  1421. CONSTANTS_SETTYPE_ABBREV);
  1422. Record.clear();
  1423. }
  1424. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  1425. Record.push_back(unsigned(IA->hasSideEffects()) |
  1426. unsigned(IA->isAlignStack()) << 1 |
  1427. unsigned(IA->getDialect()&1) << 2);
  1428. // Add the asm string.
  1429. const std::string &AsmStr = IA->getAsmString();
  1430. Record.push_back(AsmStr.size());
  1431. Record.append(AsmStr.begin(), AsmStr.end());
  1432. // Add the constraint string.
  1433. const std::string &ConstraintStr = IA->getConstraintString();
  1434. Record.push_back(ConstraintStr.size());
  1435. Record.append(ConstraintStr.begin(), ConstraintStr.end());
  1436. Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
  1437. Record.clear();
  1438. continue;
  1439. }
  1440. const Constant *C = cast<Constant>(V);
  1441. unsigned Code = -1U;
  1442. unsigned AbbrevToUse = 0;
  1443. if (C->isNullValue()) {
  1444. Code = bitc::CST_CODE_NULL;
  1445. } else if (isa<UndefValue>(C)) {
  1446. Code = bitc::CST_CODE_UNDEF;
  1447. } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
  1448. if (IV->getBitWidth() <= 64) {
  1449. uint64_t V = IV->getSExtValue();
  1450. emitSignedInt64(Record, V);
  1451. Code = bitc::CST_CODE_INTEGER;
  1452. AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
  1453. } else { // Wide integers, > 64 bits in size.
  1454. // We have an arbitrary precision integer value to write whose
  1455. // bit width is > 64. However, in canonical unsigned integer
  1456. // format it is likely that the high bits are going to be zero.
  1457. // So, we only write the number of active words.
  1458. unsigned NWords = IV->getValue().getActiveWords();
  1459. const uint64_t *RawWords = IV->getValue().getRawData();
  1460. for (unsigned i = 0; i != NWords; ++i) {
  1461. emitSignedInt64(Record, RawWords[i]);
  1462. }
  1463. Code = bitc::CST_CODE_WIDE_INTEGER;
  1464. }
  1465. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  1466. Code = bitc::CST_CODE_FLOAT;
  1467. Type *Ty = CFP->getType();
  1468. if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
  1469. Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
  1470. } else if (Ty->isX86_FP80Ty()) {
  1471. // api needed to prevent premature destruction
  1472. // bits are not in the same order as a normal i80 APInt, compensate.
  1473. APInt api = CFP->getValueAPF().bitcastToAPInt();
  1474. const uint64_t *p = api.getRawData();
  1475. Record.push_back((p[1] << 48) | (p[0] >> 16));
  1476. Record.push_back(p[0] & 0xffffLL);
  1477. } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
  1478. APInt api = CFP->getValueAPF().bitcastToAPInt();
  1479. const uint64_t *p = api.getRawData();
  1480. Record.push_back(p[0]);
  1481. Record.push_back(p[1]);
  1482. } else {
  1483. assert (0 && "Unknown FP type!");
  1484. }
  1485. } else if (isa<ConstantDataSequential>(C) &&
  1486. cast<ConstantDataSequential>(C)->isString()) {
  1487. const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
  1488. // Emit constant strings specially.
  1489. unsigned NumElts = Str->getNumElements();
  1490. // If this is a null-terminated string, use the denser CSTRING encoding.
  1491. if (Str->isCString()) {
  1492. Code = bitc::CST_CODE_CSTRING;
  1493. --NumElts; // Don't encode the null, which isn't allowed by char6.
  1494. } else {
  1495. Code = bitc::CST_CODE_STRING;
  1496. AbbrevToUse = String8Abbrev;
  1497. }
  1498. bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
  1499. bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
  1500. for (unsigned i = 0; i != NumElts; ++i) {
  1501. unsigned char V = Str->getElementAsInteger(i);
  1502. Record.push_back(V);
  1503. isCStr7 &= (V & 128) == 0;
  1504. if (isCStrChar6)
  1505. isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
  1506. }
  1507. if (isCStrChar6)
  1508. AbbrevToUse = CString6Abbrev;
  1509. else if (isCStr7)
  1510. AbbrevToUse = CString7Abbrev;
  1511. } else if (const ConstantDataSequential *CDS =
  1512. dyn_cast<ConstantDataSequential>(C)) {
  1513. Code = bitc::CST_CODE_DATA;
  1514. Type *EltTy = CDS->getType()->getElementType();
  1515. if (isa<IntegerType>(EltTy)) {
  1516. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
  1517. Record.push_back(CDS->getElementAsInteger(i));
  1518. } else {
  1519. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
  1520. Record.push_back(
  1521. CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
  1522. }
  1523. } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
  1524. isa<ConstantVector>(C)) {
  1525. Code = bitc::CST_CODE_AGGREGATE;
  1526. for (const Value *Op : C->operands())
  1527. Record.push_back(VE.getValueID(Op));
  1528. AbbrevToUse = AggregateAbbrev;
  1529. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1530. switch (CE->getOpcode()) {
  1531. default:
  1532. if (Instruction::isCast(CE->getOpcode())) {
  1533. Code = bitc::CST_CODE_CE_CAST;
  1534. Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
  1535. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  1536. Record.push_back(VE.getValueID(C->getOperand(0)));
  1537. AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
  1538. } else {
  1539. assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
  1540. Code = bitc::CST_CODE_CE_BINOP;
  1541. Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
  1542. Record.push_back(VE.getValueID(C->getOperand(0)));
  1543. Record.push_back(VE.getValueID(C->getOperand(1)));
  1544. uint64_t Flags = GetOptimizationFlags(CE);
  1545. if (Flags != 0)
  1546. Record.push_back(Flags);
  1547. }
  1548. break;
  1549. case Instruction::GetElementPtr: {
  1550. Code = bitc::CST_CODE_CE_GEP;
  1551. const auto *GO = cast<GEPOperator>(C);
  1552. if (GO->isInBounds())
  1553. Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
  1554. Record.push_back(VE.getTypeID(GO->getSourceElementType()));
  1555. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  1556. Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
  1557. Record.push_back(VE.getValueID(C->getOperand(i)));
  1558. }
  1559. break;
  1560. }
  1561. case Instruction::Select:
  1562. Code = bitc::CST_CODE_CE_SELECT;
  1563. Record.push_back(VE.getValueID(C->getOperand(0)));
  1564. Record.push_back(VE.getValueID(C->getOperand(1)));
  1565. Record.push_back(VE.getValueID(C->getOperand(2)));
  1566. break;
  1567. case Instruction::ExtractElement:
  1568. Code = bitc::CST_CODE_CE_EXTRACTELT;
  1569. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  1570. Record.push_back(VE.getValueID(C->getOperand(0)));
  1571. Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
  1572. Record.push_back(VE.getValueID(C->getOperand(1)));
  1573. break;
  1574. case Instruction::InsertElement:
  1575. Code = bitc::CST_CODE_CE_INSERTELT;
  1576. Record.push_back(VE.getValueID(C->getOperand(0)));
  1577. Record.push_back(VE.getValueID(C->getOperand(1)));
  1578. Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
  1579. Record.push_back(VE.getValueID(C->getOperand(2)));
  1580. break;
  1581. case Instruction::ShuffleVector:
  1582. // If the return type and argument types are the same, this is a
  1583. // standard shufflevector instruction. If the types are different,
  1584. // then the shuffle is widening or truncating the input vectors, and
  1585. // the argument type must also be encoded.
  1586. if (C->getType() == C->getOperand(0)->getType()) {
  1587. Code = bitc::CST_CODE_CE_SHUFFLEVEC;
  1588. } else {
  1589. Code = bitc::CST_CODE_CE_SHUFVEC_EX;
  1590. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  1591. }
  1592. Record.push_back(VE.getValueID(C->getOperand(0)));
  1593. Record.push_back(VE.getValueID(C->getOperand(1)));
  1594. Record.push_back(VE.getValueID(C->getOperand(2)));
  1595. break;
  1596. case Instruction::ICmp:
  1597. case Instruction::FCmp:
  1598. Code = bitc::CST_CODE_CE_CMP;
  1599. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  1600. Record.push_back(VE.getValueID(C->getOperand(0)));
  1601. Record.push_back(VE.getValueID(C->getOperand(1)));
  1602. Record.push_back(CE->getPredicate());
  1603. break;
  1604. }
  1605. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
  1606. Code = bitc::CST_CODE_BLOCKADDRESS;
  1607. Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
  1608. Record.push_back(VE.getValueID(BA->getFunction()));
  1609. Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
  1610. } else {
  1611. #ifndef NDEBUG
  1612. C->dump();
  1613. #endif
  1614. llvm_unreachable("Unknown constant!");
  1615. }
  1616. Stream.EmitRecord(Code, Record, AbbrevToUse);
  1617. Record.clear();
  1618. }
  1619. Stream.ExitBlock();
  1620. }
  1621. static void WriteModuleConstants(const ValueEnumerator &VE,
  1622. BitstreamWriter &Stream) {
  1623. const ValueEnumerator::ValueList &Vals = VE.getValues();
  1624. // Find the first constant to emit, which is the first non-globalvalue value.
  1625. // We know globalvalues have been emitted by WriteModuleInfo.
  1626. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1627. if (!isa<GlobalValue>(Vals[i].first)) {
  1628. WriteConstants(i, Vals.size(), VE, Stream, true);
  1629. return;
  1630. }
  1631. }
  1632. }
  1633. /// PushValueAndType - The file has to encode both the value and type id for
  1634. /// many values, because we need to know what type to create for forward
  1635. /// references. However, most operands are not forward references, so this type
  1636. /// field is not needed.
  1637. ///
  1638. /// This function adds V's value ID to Vals. If the value ID is higher than the
  1639. /// instruction ID, then it is a forward reference, and it also includes the
  1640. /// type ID. The value ID that is written is encoded relative to the InstID.
  1641. static bool PushValueAndType(const Value *V, unsigned InstID,
  1642. SmallVectorImpl<unsigned> &Vals,
  1643. ValueEnumerator &VE) {
  1644. unsigned ValID = VE.getValueID(V);
  1645. // Make encoding relative to the InstID.
  1646. Vals.push_back(InstID - ValID);
  1647. if (ValID >= InstID) {
  1648. Vals.push_back(VE.getTypeID(V->getType()));
  1649. return true;
  1650. }
  1651. return false;
  1652. }
  1653. static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
  1654. unsigned InstID, ValueEnumerator &VE) {
  1655. SmallVector<unsigned, 64> Record;
  1656. LLVMContext &C = CS.getInstruction()->getContext();
  1657. for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
  1658. const auto &Bundle = CS.getOperandBundleAt(i);
  1659. Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
  1660. for (auto &Input : Bundle.Inputs)
  1661. PushValueAndType(Input, InstID, Record, VE);
  1662. Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
  1663. Record.clear();
  1664. }
  1665. }
  1666. /// pushValue - Like PushValueAndType, but where the type of the value is
  1667. /// omitted (perhaps it was already encoded in an earlier operand).
  1668. static void pushValue(const Value *V, unsigned InstID,
  1669. SmallVectorImpl<unsigned> &Vals,
  1670. ValueEnumerator &VE) {
  1671. unsigned ValID = VE.getValueID(V);
  1672. Vals.push_back(InstID - ValID);
  1673. }
  1674. static void pushValueSigned(const Value *V, unsigned InstID,
  1675. SmallVectorImpl<uint64_t> &Vals,
  1676. ValueEnumerator &VE) {
  1677. unsigned ValID = VE.getValueID(V);
  1678. int64_t diff = ((int32_t)InstID - (int32_t)ValID);
  1679. emitSignedInt64(Vals, diff);
  1680. }
  1681. /// WriteInstruction - Emit an instruction to the specified stream.
  1682. static void WriteInstruction(const Instruction &I, unsigned InstID,
  1683. ValueEnumerator &VE, BitstreamWriter &Stream,
  1684. SmallVectorImpl<unsigned> &Vals) {
  1685. unsigned Code = 0;
  1686. unsigned AbbrevToUse = 0;
  1687. VE.setInstructionID(&I);
  1688. switch (I.getOpcode()) {
  1689. default:
  1690. if (Instruction::isCast(I.getOpcode())) {
  1691. Code = bitc::FUNC_CODE_INST_CAST;
  1692. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  1693. AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
  1694. Vals.push_back(VE.getTypeID(I.getType()));
  1695. Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
  1696. } else {
  1697. assert(isa<BinaryOperator>(I) && "Unknown instruction!");
  1698. Code = bitc::FUNC_CODE_INST_BINOP;
  1699. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  1700. AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
  1701. pushValue(I.getOperand(1), InstID, Vals, VE);
  1702. Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
  1703. uint64_t Flags = GetOptimizationFlags(&I);
  1704. if (Flags != 0) {
  1705. if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
  1706. AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
  1707. Vals.push_back(Flags);
  1708. }
  1709. }
  1710. break;
  1711. case Instruction::GetElementPtr: {
  1712. Code = bitc::FUNC_CODE_INST_GEP;
  1713. AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
  1714. auto &GEPInst = cast<GetElementPtrInst>(I);
  1715. Vals.push_back(GEPInst.isInBounds());
  1716. Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
  1717. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  1718. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  1719. break;
  1720. }
  1721. case Instruction::ExtractValue: {
  1722. Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
  1723. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1724. const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
  1725. Vals.append(EVI->idx_begin(), EVI->idx_end());
  1726. break;
  1727. }
  1728. case Instruction::InsertValue: {
  1729. Code = bitc::FUNC_CODE_INST_INSERTVAL;
  1730. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1731. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  1732. const InsertValueInst *IVI = cast<InsertValueInst>(&I);
  1733. Vals.append(IVI->idx_begin(), IVI->idx_end());
  1734. break;
  1735. }
  1736. case Instruction::Select:
  1737. Code = bitc::FUNC_CODE_INST_VSELECT;
  1738. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  1739. pushValue(I.getOperand(2), InstID, Vals, VE);
  1740. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1741. break;
  1742. case Instruction::ExtractElement:
  1743. Code = bitc::FUNC_CODE_INST_EXTRACTELT;
  1744. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1745. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  1746. break;
  1747. case Instruction::InsertElement:
  1748. Code = bitc::FUNC_CODE_INST_INSERTELT;
  1749. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1750. pushValue(I.getOperand(1), InstID, Vals, VE);
  1751. PushValueAndType(I.getOperand(2), InstID, Vals, VE);
  1752. break;
  1753. case Instruction::ShuffleVector:
  1754. Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
  1755. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1756. pushValue(I.getOperand(1), InstID, Vals, VE);
  1757. pushValue(I.getOperand(2), InstID, Vals, VE);
  1758. break;
  1759. case Instruction::ICmp:
  1760. case Instruction::FCmp: {
  1761. // compare returning Int1Ty or vector of Int1Ty
  1762. Code = bitc::FUNC_CODE_INST_CMP2;
  1763. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1764. pushValue(I.getOperand(1), InstID, Vals, VE);
  1765. Vals.push_back(cast<CmpInst>(I).getPredicate());
  1766. uint64_t Flags = GetOptimizationFlags(&I);
  1767. if (Flags != 0)
  1768. Vals.push_back(Flags);
  1769. break;
  1770. }
  1771. case Instruction::Ret:
  1772. {
  1773. Code = bitc::FUNC_CODE_INST_RET;
  1774. unsigned NumOperands = I.getNumOperands();
  1775. if (NumOperands == 0)
  1776. AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
  1777. else if (NumOperands == 1) {
  1778. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  1779. AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
  1780. } else {
  1781. for (unsigned i = 0, e = NumOperands; i != e; ++i)
  1782. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  1783. }
  1784. }
  1785. break;
  1786. case Instruction::Br:
  1787. {
  1788. Code = bitc::FUNC_CODE_INST_BR;
  1789. const BranchInst &II = cast<BranchInst>(I);
  1790. Vals.push_back(VE.getValueID(II.getSuccessor(0)));
  1791. if (II.isConditional()) {
  1792. Vals.push_back(VE.getValueID(II.getSuccessor(1)));
  1793. pushValue(II.getCondition(), InstID, Vals, VE);
  1794. }
  1795. }
  1796. break;
  1797. case Instruction::Switch:
  1798. {
  1799. Code = bitc::FUNC_CODE_INST_SWITCH;
  1800. const SwitchInst &SI = cast<SwitchInst>(I);
  1801. Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
  1802. pushValue(SI.getCondition(), InstID, Vals, VE);
  1803. Vals.push_back(VE.getValueID(SI.getDefaultDest()));
  1804. for (SwitchInst::ConstCaseIt Case : SI.cases()) {
  1805. Vals.push_back(VE.getValueID(Case.getCaseValue()));
  1806. Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
  1807. }
  1808. }
  1809. break;
  1810. case Instruction::IndirectBr:
  1811. Code = bitc::FUNC_CODE_INST_INDIRECTBR;
  1812. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  1813. // Encode the address operand as relative, but not the basic blocks.
  1814. pushValue(I.getOperand(0), InstID, Vals, VE);
  1815. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
  1816. Vals.push_back(VE.getValueID(I.getOperand(i)));
  1817. break;
  1818. case Instruction::Invoke: {
  1819. const InvokeInst *II = cast<InvokeInst>(&I);
  1820. const Value *Callee = II->getCalledValue();
  1821. FunctionType *FTy = II->getFunctionType();
  1822. if (II->hasOperandBundles())
  1823. WriteOperandBundles(Stream, II, InstID, VE);
  1824. Code = bitc::FUNC_CODE_INST_INVOKE;
  1825. Vals.push_back(VE.getAttributeID(II->getAttributes()));
  1826. Vals.push_back(II->getCallingConv() | 1 << 13);
  1827. Vals.push_back(VE.getValueID(II->getNormalDest()));
  1828. Vals.push_back(VE.getValueID(II->getUnwindDest()));
  1829. Vals.push_back(VE.getTypeID(FTy));
  1830. PushValueAndType(Callee, InstID, Vals, VE);
  1831. // Emit value #'s for the fixed parameters.
  1832. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  1833. pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
  1834. // Emit type/value pairs for varargs params.
  1835. if (FTy->isVarArg()) {
  1836. for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
  1837. i != e; ++i)
  1838. PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
  1839. }
  1840. break;
  1841. }
  1842. case Instruction::Resume:
  1843. Code = bitc::FUNC_CODE_INST_RESUME;
  1844. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1845. break;
  1846. case Instruction::CleanupRet: {
  1847. Code = bitc::FUNC_CODE_INST_CLEANUPRET;
  1848. const auto &CRI = cast<CleanupReturnInst>(I);
  1849. pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
  1850. if (CRI.hasUnwindDest())
  1851. Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
  1852. break;
  1853. }
  1854. case Instruction::CatchRet: {
  1855. Code = bitc::FUNC_CODE_INST_CATCHRET;
  1856. const auto &CRI = cast<CatchReturnInst>(I);
  1857. pushValue(CRI.getCatchPad(), InstID, Vals, VE);
  1858. Vals.push_back(VE.getValueID(CRI.getSuccessor()));
  1859. break;
  1860. }
  1861. case Instruction::CleanupPad:
  1862. case Instruction::CatchPad: {
  1863. const auto &FuncletPad = cast<FuncletPadInst>(I);
  1864. Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
  1865. : bitc::FUNC_CODE_INST_CLEANUPPAD;
  1866. pushValue(FuncletPad.getParentPad(), InstID, Vals, VE);
  1867. unsigned NumArgOperands = FuncletPad.getNumArgOperands();
  1868. Vals.push_back(NumArgOperands);
  1869. for (unsigned Op = 0; Op != NumArgOperands; ++Op)
  1870. PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE);
  1871. break;
  1872. }
  1873. case Instruction::CatchSwitch: {
  1874. Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
  1875. const auto &CatchSwitch = cast<CatchSwitchInst>(I);
  1876. pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE);
  1877. unsigned NumHandlers = CatchSwitch.getNumHandlers();
  1878. Vals.push_back(NumHandlers);
  1879. for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
  1880. Vals.push_back(VE.getValueID(CatchPadBB));
  1881. if (CatchSwitch.hasUnwindDest())
  1882. Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
  1883. break;
  1884. }
  1885. case Instruction::Unreachable:
  1886. Code = bitc::FUNC_CODE_INST_UNREACHABLE;
  1887. AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
  1888. break;
  1889. case Instruction::PHI: {
  1890. const PHINode &PN = cast<PHINode>(I);
  1891. Code = bitc::FUNC_CODE_INST_PHI;
  1892. // With the newer instruction encoding, forward references could give
  1893. // negative valued IDs. This is most common for PHIs, so we use
  1894. // signed VBRs.
  1895. SmallVector<uint64_t, 128> Vals64;
  1896. Vals64.push_back(VE.getTypeID(PN.getType()));
  1897. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
  1898. pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
  1899. Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
  1900. }
  1901. // Emit a Vals64 vector and exit.
  1902. Stream.EmitRecord(Code, Vals64, AbbrevToUse);
  1903. Vals64.clear();
  1904. return;
  1905. }
  1906. case Instruction::LandingPad: {
  1907. const LandingPadInst &LP = cast<LandingPadInst>(I);
  1908. Code = bitc::FUNC_CODE_INST_LANDINGPAD;
  1909. Vals.push_back(VE.getTypeID(LP.getType()));
  1910. Vals.push_back(LP.isCleanup());
  1911. Vals.push_back(LP.getNumClauses());
  1912. for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
  1913. if (LP.isCatch(I))
  1914. Vals.push_back(LandingPadInst::Catch);
  1915. else
  1916. Vals.push_back(LandingPadInst::Filter);
  1917. PushValueAndType(LP.getClause(I), InstID, Vals, VE);
  1918. }
  1919. break;
  1920. }
  1921. case Instruction::Alloca: {
  1922. Code = bitc::FUNC_CODE_INST_ALLOCA;
  1923. const AllocaInst &AI = cast<AllocaInst>(I);
  1924. Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
  1925. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  1926. Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
  1927. unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
  1928. assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
  1929. "not enough bits for maximum alignment");
  1930. assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
  1931. AlignRecord |= AI.isUsedWithInAlloca() << 5;
  1932. AlignRecord |= 1 << 6;
  1933. // Reserve bit 7 for SwiftError flag.
  1934. // AlignRecord |= AI.isSwiftError() << 7;
  1935. Vals.push_back(AlignRecord);
  1936. break;
  1937. }
  1938. case Instruction::Load:
  1939. if (cast<LoadInst>(I).isAtomic()) {
  1940. Code = bitc::FUNC_CODE_INST_LOADATOMIC;
  1941. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1942. } else {
  1943. Code = bitc::FUNC_CODE_INST_LOAD;
  1944. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
  1945. AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
  1946. }
  1947. Vals.push_back(VE.getTypeID(I.getType()));
  1948. Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
  1949. Vals.push_back(cast<LoadInst>(I).isVolatile());
  1950. if (cast<LoadInst>(I).isAtomic()) {
  1951. Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
  1952. Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
  1953. }
  1954. break;
  1955. case Instruction::Store:
  1956. if (cast<StoreInst>(I).isAtomic())
  1957. Code = bitc::FUNC_CODE_INST_STOREATOMIC;
  1958. else
  1959. Code = bitc::FUNC_CODE_INST_STORE;
  1960. PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
  1961. PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
  1962. Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
  1963. Vals.push_back(cast<StoreInst>(I).isVolatile());
  1964. if (cast<StoreInst>(I).isAtomic()) {
  1965. Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
  1966. Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
  1967. }
  1968. break;
  1969. case Instruction::AtomicCmpXchg:
  1970. Code = bitc::FUNC_CODE_INST_CMPXCHG;
  1971. PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
  1972. PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp.
  1973. pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
  1974. Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
  1975. Vals.push_back(GetEncodedOrdering(
  1976. cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
  1977. Vals.push_back(GetEncodedSynchScope(
  1978. cast<AtomicCmpXchgInst>(I).getSynchScope()));
  1979. Vals.push_back(GetEncodedOrdering(
  1980. cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
  1981. Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
  1982. break;
  1983. case Instruction::AtomicRMW:
  1984. Code = bitc::FUNC_CODE_INST_ATOMICRMW;
  1985. PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
  1986. pushValue(I.getOperand(1), InstID, Vals, VE); // val.
  1987. Vals.push_back(GetEncodedRMWOperation(
  1988. cast<AtomicRMWInst>(I).getOperation()));
  1989. Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
  1990. Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
  1991. Vals.push_back(GetEncodedSynchScope(
  1992. cast<AtomicRMWInst>(I).getSynchScope()));
  1993. break;
  1994. case Instruction::Fence:
  1995. Code = bitc::FUNC_CODE_INST_FENCE;
  1996. Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
  1997. Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
  1998. break;
  1999. case Instruction::Call: {
  2000. const CallInst &CI = cast<CallInst>(I);
  2001. FunctionType *FTy = CI.getFunctionType();
  2002. if (CI.hasOperandBundles())
  2003. WriteOperandBundles(Stream, &CI, InstID, VE);
  2004. Code = bitc::FUNC_CODE_INST_CALL;
  2005. Vals.push_back(VE.getAttributeID(CI.getAttributes()));
  2006. unsigned Flags = GetOptimizationFlags(&I);
  2007. Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
  2008. unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
  2009. unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
  2010. 1 << bitc::CALL_EXPLICIT_TYPE |
  2011. unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
  2012. unsigned(Flags != 0) << bitc::CALL_FMF);
  2013. if (Flags != 0)
  2014. Vals.push_back(Flags);
  2015. Vals.push_back(VE.getTypeID(FTy));
  2016. PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
  2017. // Emit value #'s for the fixed parameters.
  2018. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  2019. // Check for labels (can happen with asm labels).
  2020. if (FTy->getParamType(i)->isLabelTy())
  2021. Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
  2022. else
  2023. pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
  2024. }
  2025. // Emit type/value pairs for varargs params.
  2026. if (FTy->isVarArg()) {
  2027. for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
  2028. i != e; ++i)
  2029. PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
  2030. }
  2031. break;
  2032. }
  2033. case Instruction::VAArg:
  2034. Code = bitc::FUNC_CODE_INST_VAARG;
  2035. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
  2036. pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
  2037. Vals.push_back(VE.getTypeID(I.getType())); // restype.
  2038. break;
  2039. }
  2040. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  2041. Vals.clear();
  2042. }
  2043. /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
  2044. /// BitcodeStartBit and ModuleSummaryIndex are only passed for the module-level
  2045. /// VST, where we are including a function bitcode index and need to
  2046. /// backpatch the VST forward declaration record.
  2047. static void WriteValueSymbolTable(
  2048. const ValueSymbolTable &VST, const ValueEnumerator &VE,
  2049. BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
  2050. uint64_t BitcodeStartBit = 0,
  2051. DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>>
  2052. *FunctionIndex = nullptr) {
  2053. if (VST.empty()) {
  2054. // WriteValueSymbolTableForwardDecl should have returned early as
  2055. // well. Ensure this handling remains in sync by asserting that
  2056. // the placeholder offset is not set.
  2057. assert(VSTOffsetPlaceholder == 0);
  2058. return;
  2059. }
  2060. if (VSTOffsetPlaceholder > 0) {
  2061. // Get the offset of the VST we are writing, and backpatch it into
  2062. // the VST forward declaration record.
  2063. uint64_t VSTOffset = Stream.GetCurrentBitNo();
  2064. // The BitcodeStartBit was the stream offset of the actual bitcode
  2065. // (e.g. excluding any initial darwin header).
  2066. VSTOffset -= BitcodeStartBit;
  2067. assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
  2068. Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
  2069. }
  2070. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  2071. // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
  2072. // records, which are not used in the per-function VSTs.
  2073. unsigned FnEntry8BitAbbrev;
  2074. unsigned FnEntry7BitAbbrev;
  2075. unsigned FnEntry6BitAbbrev;
  2076. if (VSTOffsetPlaceholder > 0) {
  2077. // 8-bit fixed-width VST_CODE_FNENTRY function strings.
  2078. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2079. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
  2080. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2081. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2082. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2083. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2084. FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
  2085. // 7-bit fixed width VST_CODE_FNENTRY function strings.
  2086. Abbv = new BitCodeAbbrev();
  2087. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
  2088. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2089. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2090. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2091. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2092. FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
  2093. // 6-bit char6 VST_CODE_FNENTRY function strings.
  2094. Abbv = new BitCodeAbbrev();
  2095. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
  2096. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2097. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2098. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2099. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2100. FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
  2101. }
  2102. // FIXME: Set up the abbrev, we know how many values there are!
  2103. // FIXME: We know if the type names can use 7-bit ascii.
  2104. SmallVector<unsigned, 64> NameVals;
  2105. for (const ValueName &Name : VST) {
  2106. // Figure out the encoding to use for the name.
  2107. StringEncoding Bits =
  2108. getStringEncoding(Name.getKeyData(), Name.getKeyLength());
  2109. unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
  2110. NameVals.push_back(VE.getValueID(Name.getValue()));
  2111. Function *F = dyn_cast<Function>(Name.getValue());
  2112. if (!F) {
  2113. // If value is an alias, need to get the aliased base object to
  2114. // see if it is a function.
  2115. auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
  2116. if (GA && GA->getBaseObject())
  2117. F = dyn_cast<Function>(GA->getBaseObject());
  2118. }
  2119. // VST_CODE_ENTRY: [valueid, namechar x N]
  2120. // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
  2121. // VST_CODE_BBENTRY: [bbid, namechar x N]
  2122. unsigned Code;
  2123. if (isa<BasicBlock>(Name.getValue())) {
  2124. Code = bitc::VST_CODE_BBENTRY;
  2125. if (Bits == SE_Char6)
  2126. AbbrevToUse = VST_BBENTRY_6_ABBREV;
  2127. } else if (F && !F->isDeclaration()) {
  2128. // Must be the module-level VST, where we pass in the Index and
  2129. // have a VSTOffsetPlaceholder. The function-level VST should not
  2130. // contain any Function symbols.
  2131. assert(FunctionIndex);
  2132. assert(VSTOffsetPlaceholder > 0);
  2133. // Save the word offset of the function (from the start of the
  2134. // actual bitcode written to the stream).
  2135. uint64_t BitcodeIndex =
  2136. (*FunctionIndex)[F]->bitcodeIndex() - BitcodeStartBit;
  2137. assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
  2138. NameVals.push_back(BitcodeIndex / 32);
  2139. Code = bitc::VST_CODE_FNENTRY;
  2140. AbbrevToUse = FnEntry8BitAbbrev;
  2141. if (Bits == SE_Char6)
  2142. AbbrevToUse = FnEntry6BitAbbrev;
  2143. else if (Bits == SE_Fixed7)
  2144. AbbrevToUse = FnEntry7BitAbbrev;
  2145. } else {
  2146. Code = bitc::VST_CODE_ENTRY;
  2147. if (Bits == SE_Char6)
  2148. AbbrevToUse = VST_ENTRY_6_ABBREV;
  2149. else if (Bits == SE_Fixed7)
  2150. AbbrevToUse = VST_ENTRY_7_ABBREV;
  2151. }
  2152. for (const auto P : Name.getKey())
  2153. NameVals.push_back((unsigned char)P);
  2154. // Emit the finished record.
  2155. Stream.EmitRecord(Code, NameVals, AbbrevToUse);
  2156. NameVals.clear();
  2157. }
  2158. Stream.ExitBlock();
  2159. }
  2160. /// Emit function names and summary offsets for the combined index
  2161. /// used by ThinLTO.
  2162. static void
  2163. WriteCombinedValueSymbolTable(const ModuleSummaryIndex &Index,
  2164. BitstreamWriter &Stream,
  2165. std::map<uint64_t, unsigned> &GUIDToValueIdMap,
  2166. uint64_t VSTOffsetPlaceholder) {
  2167. assert(VSTOffsetPlaceholder > 0 && "Expected non-zero VSTOffsetPlaceholder");
  2168. // Get the offset of the VST we are writing, and backpatch it into
  2169. // the VST forward declaration record.
  2170. uint64_t VSTOffset = Stream.GetCurrentBitNo();
  2171. assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
  2172. Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
  2173. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  2174. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2175. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_GVDEFENTRY));
  2176. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  2177. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // sumoffset
  2178. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // guid
  2179. unsigned DefEntryAbbrev = Stream.EmitAbbrev(Abbv);
  2180. Abbv = new BitCodeAbbrev();
  2181. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
  2182. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  2183. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
  2184. unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv);
  2185. SmallVector<uint64_t, 64> NameVals;
  2186. for (const auto &FII : Index) {
  2187. uint64_t FuncGUID = FII.first;
  2188. const auto &VMI = GUIDToValueIdMap.find(FuncGUID);
  2189. assert(VMI != GUIDToValueIdMap.end());
  2190. for (const auto &FI : FII.second) {
  2191. // VST_CODE_COMBINED_GVDEFENTRY: [valueid, sumoffset, guid]
  2192. NameVals.push_back(VMI->second);
  2193. NameVals.push_back(FI->bitcodeIndex());
  2194. NameVals.push_back(FuncGUID);
  2195. // Emit the finished record.
  2196. Stream.EmitRecord(bitc::VST_CODE_COMBINED_GVDEFENTRY, NameVals,
  2197. DefEntryAbbrev);
  2198. NameVals.clear();
  2199. }
  2200. GUIDToValueIdMap.erase(VMI);
  2201. }
  2202. for (const auto &GVI : GUIDToValueIdMap) {
  2203. // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
  2204. NameVals.push_back(GVI.second);
  2205. NameVals.push_back(GVI.first);
  2206. // Emit the finished record.
  2207. Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
  2208. NameVals.clear();
  2209. }
  2210. Stream.ExitBlock();
  2211. }
  2212. static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
  2213. BitstreamWriter &Stream) {
  2214. assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
  2215. unsigned Code;
  2216. if (isa<BasicBlock>(Order.V))
  2217. Code = bitc::USELIST_CODE_BB;
  2218. else
  2219. Code = bitc::USELIST_CODE_DEFAULT;
  2220. SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
  2221. Record.push_back(VE.getValueID(Order.V));
  2222. Stream.EmitRecord(Code, Record);
  2223. }
  2224. static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
  2225. BitstreamWriter &Stream) {
  2226. assert(VE.shouldPreserveUseListOrder() &&
  2227. "Expected to be preserving use-list order");
  2228. auto hasMore = [&]() {
  2229. return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
  2230. };
  2231. if (!hasMore())
  2232. // Nothing to do.
  2233. return;
  2234. Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
  2235. while (hasMore()) {
  2236. WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
  2237. VE.UseListOrders.pop_back();
  2238. }
  2239. Stream.ExitBlock();
  2240. }
  2241. // Walk through the operands of a given User via worklist iteration and populate
  2242. // the set of GlobalValue references encountered. Invoked either on an
  2243. // Instruction or a GlobalVariable (which walks its initializer).
  2244. static void findRefEdges(const User *CurUser, const ValueEnumerator &VE,
  2245. DenseSet<unsigned> &RefEdges,
  2246. SmallPtrSet<const User *, 8> &Visited) {
  2247. SmallVector<const User *, 32> Worklist;
  2248. Worklist.push_back(CurUser);
  2249. while (!Worklist.empty()) {
  2250. const User *U = Worklist.pop_back_val();
  2251. if (!Visited.insert(U).second)
  2252. continue;
  2253. ImmutableCallSite CS(U);
  2254. for (const auto &OI : U->operands()) {
  2255. const User *Operand = dyn_cast<User>(OI);
  2256. if (!Operand)
  2257. continue;
  2258. if (isa<BlockAddress>(Operand))
  2259. continue;
  2260. if (isa<GlobalValue>(Operand)) {
  2261. // We have a reference to a global value. This should be added to
  2262. // the reference set unless it is a callee. Callees are handled
  2263. // specially by WriteFunction and are added to a separate list.
  2264. if (!(CS && CS.isCallee(&OI)))
  2265. RefEdges.insert(VE.getValueID(Operand));
  2266. continue;
  2267. }
  2268. Worklist.push_back(Operand);
  2269. }
  2270. }
  2271. }
  2272. /// Emit a function body to the module stream.
  2273. static void WriteFunction(
  2274. const Function &F, const Module *M, ValueEnumerator &VE,
  2275. BitstreamWriter &Stream,
  2276. DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> &FunctionIndex,
  2277. bool EmitSummaryIndex) {
  2278. // Save the bitcode index of the start of this function block for recording
  2279. // in the VST.
  2280. uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
  2281. bool HasProfileData = F.getEntryCount().hasValue();
  2282. std::unique_ptr<BlockFrequencyInfo> BFI;
  2283. if (EmitSummaryIndex && HasProfileData) {
  2284. Function &Func = const_cast<Function &>(F);
  2285. LoopInfo LI{DominatorTree(Func)};
  2286. BranchProbabilityInfo BPI{Func, LI};
  2287. BFI = llvm::make_unique<BlockFrequencyInfo>(Func, BPI, LI);
  2288. }
  2289. Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
  2290. VE.incorporateFunction(F);
  2291. SmallVector<unsigned, 64> Vals;
  2292. // Emit the number of basic blocks, so the reader can create them ahead of
  2293. // time.
  2294. Vals.push_back(VE.getBasicBlocks().size());
  2295. Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
  2296. Vals.clear();
  2297. // If there are function-local constants, emit them now.
  2298. unsigned CstStart, CstEnd;
  2299. VE.getFunctionConstantRange(CstStart, CstEnd);
  2300. WriteConstants(CstStart, CstEnd, VE, Stream, false);
  2301. // If there is function-local metadata, emit it now.
  2302. writeFunctionMetadata(F, VE, Stream);
  2303. // Keep a running idea of what the instruction ID is.
  2304. unsigned InstID = CstEnd;
  2305. bool NeedsMetadataAttachment = F.hasMetadata();
  2306. DILocation *LastDL = nullptr;
  2307. unsigned NumInsts = 0;
  2308. // Map from callee ValueId to profile count. Used to accumulate profile
  2309. // counts for all static calls to a given callee.
  2310. DenseMap<unsigned, CalleeInfo> CallGraphEdges;
  2311. DenseSet<unsigned> RefEdges;
  2312. SmallPtrSet<const User *, 8> Visited;
  2313. // Finally, emit all the instructions, in order.
  2314. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  2315. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  2316. I != E; ++I) {
  2317. WriteInstruction(*I, InstID, VE, Stream, Vals);
  2318. if (!isa<DbgInfoIntrinsic>(I))
  2319. ++NumInsts;
  2320. if (!I->getType()->isVoidTy())
  2321. ++InstID;
  2322. if (EmitSummaryIndex) {
  2323. if (auto CS = ImmutableCallSite(&*I)) {
  2324. auto *CalledFunction = CS.getCalledFunction();
  2325. if (CalledFunction && CalledFunction->hasName() &&
  2326. !CalledFunction->isIntrinsic()) {
  2327. auto ScaledCount = BFI ? BFI->getBlockProfileCount(&*BB) : None;
  2328. unsigned CalleeId = VE.getValueID(
  2329. M->getValueSymbolTable().lookup(CalledFunction->getName()));
  2330. CallGraphEdges[CalleeId] +=
  2331. (ScaledCount ? ScaledCount.getValue() : 0);
  2332. }
  2333. }
  2334. findRefEdges(&*I, VE, RefEdges, Visited);
  2335. }
  2336. // If the instruction has metadata, write a metadata attachment later.
  2337. NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
  2338. // If the instruction has a debug location, emit it.
  2339. DILocation *DL = I->getDebugLoc();
  2340. if (!DL)
  2341. continue;
  2342. if (DL == LastDL) {
  2343. // Just repeat the same debug loc as last time.
  2344. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
  2345. continue;
  2346. }
  2347. Vals.push_back(DL->getLine());
  2348. Vals.push_back(DL->getColumn());
  2349. Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
  2350. Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
  2351. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
  2352. Vals.clear();
  2353. LastDL = DL;
  2354. }
  2355. std::unique_ptr<FunctionSummary> FuncSummary;
  2356. if (EmitSummaryIndex) {
  2357. FuncSummary = llvm::make_unique<FunctionSummary>(F.getLinkage(), NumInsts);
  2358. FuncSummary->addCallGraphEdges(CallGraphEdges);
  2359. FuncSummary->addRefEdges(RefEdges);
  2360. }
  2361. FunctionIndex[&F] =
  2362. llvm::make_unique<GlobalValueInfo>(BitcodeIndex, std::move(FuncSummary));
  2363. // Emit names for all the instructions etc.
  2364. WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
  2365. if (NeedsMetadataAttachment)
  2366. WriteMetadataAttachment(F, VE, Stream);
  2367. if (VE.shouldPreserveUseListOrder())
  2368. WriteUseListBlock(&F, VE, Stream);
  2369. VE.purgeFunction();
  2370. Stream.ExitBlock();
  2371. }
  2372. // Emit blockinfo, which defines the standard abbreviations etc.
  2373. static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  2374. // We only want to emit block info records for blocks that have multiple
  2375. // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
  2376. // Other blocks can define their abbrevs inline.
  2377. Stream.EnterBlockInfoBlock(2);
  2378. { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
  2379. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2380. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
  2381. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2382. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2383. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2384. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  2385. Abbv) != VST_ENTRY_8_ABBREV)
  2386. llvm_unreachable("Unexpected abbrev ordering!");
  2387. }
  2388. { // 7-bit fixed width VST_CODE_ENTRY strings.
  2389. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2390. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  2391. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2392. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2393. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2394. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  2395. Abbv) != VST_ENTRY_7_ABBREV)
  2396. llvm_unreachable("Unexpected abbrev ordering!");
  2397. }
  2398. { // 6-bit char6 VST_CODE_ENTRY strings.
  2399. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2400. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  2401. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2402. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2403. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2404. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  2405. Abbv) != VST_ENTRY_6_ABBREV)
  2406. llvm_unreachable("Unexpected abbrev ordering!");
  2407. }
  2408. { // 6-bit char6 VST_CODE_BBENTRY strings.
  2409. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2410. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
  2411. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2412. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2413. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2414. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  2415. Abbv) != VST_BBENTRY_6_ABBREV)
  2416. llvm_unreachable("Unexpected abbrev ordering!");
  2417. }
  2418. { // SETTYPE abbrev for CONSTANTS_BLOCK.
  2419. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2420. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
  2421. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  2422. VE.computeBitsRequiredForTypeIndicies()));
  2423. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  2424. Abbv) != CONSTANTS_SETTYPE_ABBREV)
  2425. llvm_unreachable("Unexpected abbrev ordering!");
  2426. }
  2427. { // INTEGER abbrev for CONSTANTS_BLOCK.
  2428. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2429. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
  2430. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2431. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  2432. Abbv) != CONSTANTS_INTEGER_ABBREV)
  2433. llvm_unreachable("Unexpected abbrev ordering!");
  2434. }
  2435. { // CE_CAST abbrev for CONSTANTS_BLOCK.
  2436. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2437. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
  2438. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
  2439. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
  2440. VE.computeBitsRequiredForTypeIndicies()));
  2441. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2442. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  2443. Abbv) != CONSTANTS_CE_CAST_Abbrev)
  2444. llvm_unreachable("Unexpected abbrev ordering!");
  2445. }
  2446. { // NULL abbrev for CONSTANTS_BLOCK.
  2447. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2448. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
  2449. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  2450. Abbv) != CONSTANTS_NULL_Abbrev)
  2451. llvm_unreachable("Unexpected abbrev ordering!");
  2452. }
  2453. // FIXME: This should only use space for first class types!
  2454. { // INST_LOAD abbrev for FUNCTION_BLOCK.
  2455. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2456. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
  2457. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
  2458. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  2459. VE.computeBitsRequiredForTypeIndicies()));
  2460. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
  2461. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
  2462. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2463. Abbv) != FUNCTION_INST_LOAD_ABBREV)
  2464. llvm_unreachable("Unexpected abbrev ordering!");
  2465. }
  2466. { // INST_BINOP abbrev for FUNCTION_BLOCK.
  2467. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2468. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  2469. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2470. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  2471. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2472. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2473. Abbv) != FUNCTION_INST_BINOP_ABBREV)
  2474. llvm_unreachable("Unexpected abbrev ordering!");
  2475. }
  2476. { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
  2477. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2478. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  2479. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2480. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  2481. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2482. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
  2483. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2484. Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
  2485. llvm_unreachable("Unexpected abbrev ordering!");
  2486. }
  2487. { // INST_CAST abbrev for FUNCTION_BLOCK.
  2488. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2489. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
  2490. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
  2491. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  2492. VE.computeBitsRequiredForTypeIndicies()));
  2493. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2494. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2495. Abbv) != FUNCTION_INST_CAST_ABBREV)
  2496. llvm_unreachable("Unexpected abbrev ordering!");
  2497. }
  2498. { // INST_RET abbrev for FUNCTION_BLOCK.
  2499. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2500. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  2501. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2502. Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
  2503. llvm_unreachable("Unexpected abbrev ordering!");
  2504. }
  2505. { // INST_RET abbrev for FUNCTION_BLOCK.
  2506. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2507. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  2508. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
  2509. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2510. Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
  2511. llvm_unreachable("Unexpected abbrev ordering!");
  2512. }
  2513. { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
  2514. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2515. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
  2516. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2517. Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
  2518. llvm_unreachable("Unexpected abbrev ordering!");
  2519. }
  2520. {
  2521. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2522. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
  2523. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  2524. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  2525. Log2_32_Ceil(VE.getTypes().size() + 1)));
  2526. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2527. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  2528. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2529. FUNCTION_INST_GEP_ABBREV)
  2530. llvm_unreachable("Unexpected abbrev ordering!");
  2531. }
  2532. Stream.ExitBlock();
  2533. }
  2534. /// Write the module path strings, currently only used when generating
  2535. /// a combined index file.
  2536. static void WriteModStrings(const ModuleSummaryIndex &I,
  2537. BitstreamWriter &Stream) {
  2538. Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
  2539. // TODO: See which abbrev sizes we actually need to emit
  2540. // 8-bit fixed-width MST_ENTRY strings.
  2541. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2542. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  2543. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2544. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2545. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2546. unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
  2547. // 7-bit fixed width MST_ENTRY strings.
  2548. Abbv = new BitCodeAbbrev();
  2549. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  2550. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2551. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2552. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2553. unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
  2554. // 6-bit char6 MST_ENTRY strings.
  2555. Abbv = new BitCodeAbbrev();
  2556. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  2557. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2558. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2559. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2560. unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
  2561. // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
  2562. Abbv = new BitCodeAbbrev();
  2563. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
  2564. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2565. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2566. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2567. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2568. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2569. unsigned AbbrevHash = Stream.EmitAbbrev(Abbv);
  2570. SmallVector<unsigned, 64> Vals;
  2571. for (const auto &MPSE : I.modulePaths()) {
  2572. StringEncoding Bits =
  2573. getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
  2574. unsigned AbbrevToUse = Abbrev8Bit;
  2575. if (Bits == SE_Char6)
  2576. AbbrevToUse = Abbrev6Bit;
  2577. else if (Bits == SE_Fixed7)
  2578. AbbrevToUse = Abbrev7Bit;
  2579. Vals.push_back(MPSE.getValue().first);
  2580. for (const auto P : MPSE.getKey())
  2581. Vals.push_back((unsigned char)P);
  2582. // Emit the finished record.
  2583. Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
  2584. Vals.clear();
  2585. // Emit an optional hash for the module now
  2586. auto &Hash = MPSE.getValue().second;
  2587. bool AllZero = true; // Detect if the hash is empty, and do not generate it
  2588. for (auto Val : Hash) {
  2589. if (Val)
  2590. AllZero = false;
  2591. Vals.push_back(Val);
  2592. }
  2593. if (!AllZero) {
  2594. // Emit the hash record.
  2595. Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
  2596. }
  2597. Vals.clear();
  2598. }
  2599. Stream.ExitBlock();
  2600. }
  2601. // Helper to emit a single function summary record.
  2602. static void WritePerModuleFunctionSummaryRecord(
  2603. SmallVector<uint64_t, 64> &NameVals, FunctionSummary *FS, unsigned ValueID,
  2604. unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
  2605. BitstreamWriter &Stream, const Function &F) {
  2606. assert(FS);
  2607. NameVals.push_back(ValueID);
  2608. NameVals.push_back(getEncodedLinkage(FS->linkage()));
  2609. NameVals.push_back(FS->instCount());
  2610. NameVals.push_back(FS->refs().size());
  2611. for (auto &RI : FS->refs())
  2612. NameVals.push_back(RI);
  2613. bool HasProfileData = F.getEntryCount().hasValue();
  2614. for (auto &ECI : FS->calls()) {
  2615. NameVals.push_back(ECI.first);
  2616. assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite");
  2617. NameVals.push_back(ECI.second.CallsiteCount);
  2618. if (HasProfileData)
  2619. NameVals.push_back(ECI.second.ProfileCount);
  2620. }
  2621. unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
  2622. unsigned Code =
  2623. (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
  2624. // Emit the finished record.
  2625. Stream.EmitRecord(Code, NameVals, FSAbbrev);
  2626. NameVals.clear();
  2627. }
  2628. // Collect the global value references in the given variable's initializer,
  2629. // and emit them in a summary record.
  2630. static void WriteModuleLevelReferences(const GlobalVariable &V,
  2631. const ValueEnumerator &VE,
  2632. SmallVector<uint64_t, 64> &NameVals,
  2633. unsigned FSModRefsAbbrev,
  2634. BitstreamWriter &Stream) {
  2635. // Only interested in recording variable defs in the summary.
  2636. if (V.isDeclaration())
  2637. return;
  2638. DenseSet<unsigned> RefEdges;
  2639. SmallPtrSet<const User *, 8> Visited;
  2640. findRefEdges(&V, VE, RefEdges, Visited);
  2641. NameVals.push_back(VE.getValueID(&V));
  2642. NameVals.push_back(getEncodedLinkage(V.getLinkage()));
  2643. for (auto RefId : RefEdges) {
  2644. NameVals.push_back(RefId);
  2645. }
  2646. Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
  2647. FSModRefsAbbrev);
  2648. NameVals.clear();
  2649. }
  2650. /// Emit the per-module summary section alongside the rest of
  2651. /// the module's bitcode.
  2652. static void WritePerModuleGlobalValueSummary(
  2653. DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> &FunctionIndex,
  2654. const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream) {
  2655. if (M->empty())
  2656. return;
  2657. Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
  2658. // Abbrev for FS_PERMODULE.
  2659. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2660. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
  2661. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  2662. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
  2663. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  2664. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  2665. // numrefs x valueid, n x (valueid, callsitecount)
  2666. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2667. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2668. unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
  2669. // Abbrev for FS_PERMODULE_PROFILE.
  2670. Abbv = new BitCodeAbbrev();
  2671. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
  2672. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  2673. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
  2674. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  2675. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  2676. // numrefs x valueid, n x (valueid, callsitecount, profilecount)
  2677. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2678. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2679. unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
  2680. // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
  2681. Abbv = new BitCodeAbbrev();
  2682. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
  2683. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  2684. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
  2685. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
  2686. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2687. unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
  2688. SmallVector<uint64_t, 64> NameVals;
  2689. // Iterate over the list of functions instead of the FunctionIndex map to
  2690. // ensure the ordering is stable.
  2691. for (const Function &F : *M) {
  2692. if (F.isDeclaration())
  2693. continue;
  2694. // Skip anonymous functions. We will emit a function summary for
  2695. // any aliases below.
  2696. if (!F.hasName())
  2697. continue;
  2698. assert(FunctionIndex.count(&F) == 1);
  2699. WritePerModuleFunctionSummaryRecord(
  2700. NameVals, cast<FunctionSummary>(FunctionIndex[&F]->summary()),
  2701. VE.getValueID(M->getValueSymbolTable().lookup(F.getName())),
  2702. FSCallsAbbrev, FSCallsProfileAbbrev, Stream, F);
  2703. }
  2704. for (const GlobalAlias &A : M->aliases()) {
  2705. if (!A.getBaseObject())
  2706. continue;
  2707. const Function *F = dyn_cast<Function>(A.getBaseObject());
  2708. if (!F || F->isDeclaration())
  2709. continue;
  2710. assert(FunctionIndex.count(F) == 1);
  2711. FunctionSummary *FS =
  2712. cast<FunctionSummary>(FunctionIndex[F]->summary());
  2713. // Add the alias to the reference list of aliasee function.
  2714. FS->addRefEdge(
  2715. VE.getValueID(M->getValueSymbolTable().lookup(A.getName())));
  2716. WritePerModuleFunctionSummaryRecord(
  2717. NameVals, FS,
  2718. VE.getValueID(M->getValueSymbolTable().lookup(A.getName())),
  2719. FSCallsAbbrev, FSCallsProfileAbbrev, Stream, *F);
  2720. }
  2721. // Capture references from GlobalVariable initializers, which are outside
  2722. // of a function scope.
  2723. for (const GlobalVariable &G : M->globals())
  2724. WriteModuleLevelReferences(G, VE, NameVals, FSModRefsAbbrev, Stream);
  2725. for (const GlobalAlias &A : M->aliases())
  2726. if (auto *GV = dyn_cast<GlobalVariable>(A.getBaseObject()))
  2727. WriteModuleLevelReferences(*GV, VE, NameVals, FSModRefsAbbrev, Stream);
  2728. Stream.ExitBlock();
  2729. }
  2730. /// Emit the combined summary section into the combined index file.
  2731. static void WriteCombinedGlobalValueSummary(
  2732. const ModuleSummaryIndex &I, BitstreamWriter &Stream,
  2733. std::map<uint64_t, unsigned> &GUIDToValueIdMap, unsigned GlobalValueId) {
  2734. Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
  2735. // Abbrev for FS_COMBINED.
  2736. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2737. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
  2738. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  2739. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
  2740. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  2741. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  2742. // numrefs x valueid, n x (valueid, callsitecount)
  2743. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2744. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2745. unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
  2746. // Abbrev for FS_COMBINED_PROFILE.
  2747. Abbv = new BitCodeAbbrev();
  2748. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
  2749. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  2750. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
  2751. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  2752. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  2753. // numrefs x valueid, n x (valueid, callsitecount, profilecount)
  2754. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2755. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2756. unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
  2757. // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
  2758. Abbv = new BitCodeAbbrev();
  2759. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
  2760. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  2761. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
  2762. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
  2763. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2764. unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
  2765. SmallVector<uint64_t, 64> NameVals;
  2766. for (const auto &FII : I) {
  2767. for (auto &FI : FII.second) {
  2768. GlobalValueSummary *S = FI->summary();
  2769. assert(S);
  2770. if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
  2771. NameVals.push_back(I.getModuleId(VS->modulePath()));
  2772. NameVals.push_back(getEncodedLinkage(VS->linkage()));
  2773. for (auto &RI : VS->refs()) {
  2774. const auto &VMI = GUIDToValueIdMap.find(RI);
  2775. unsigned RefId;
  2776. // If this GUID doesn't have an entry, assign one.
  2777. if (VMI == GUIDToValueIdMap.end()) {
  2778. GUIDToValueIdMap[RI] = ++GlobalValueId;
  2779. RefId = GlobalValueId;
  2780. } else {
  2781. RefId = VMI->second;
  2782. }
  2783. NameVals.push_back(RefId);
  2784. }
  2785. // Record the starting offset of this summary entry for use
  2786. // in the VST entry. Add the current code size since the
  2787. // reader will invoke readRecord after the abbrev id read.
  2788. FI->setBitcodeIndex(Stream.GetCurrentBitNo() +
  2789. Stream.GetAbbrevIDWidth());
  2790. // Emit the finished record.
  2791. Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
  2792. FSModRefsAbbrev);
  2793. NameVals.clear();
  2794. continue;
  2795. }
  2796. auto *FS = cast<FunctionSummary>(S);
  2797. NameVals.push_back(I.getModuleId(FS->modulePath()));
  2798. NameVals.push_back(getEncodedLinkage(FS->linkage()));
  2799. NameVals.push_back(FS->instCount());
  2800. NameVals.push_back(FS->refs().size());
  2801. for (auto &RI : FS->refs()) {
  2802. const auto &VMI = GUIDToValueIdMap.find(RI);
  2803. unsigned RefId;
  2804. // If this GUID doesn't have an entry, assign one.
  2805. if (VMI == GUIDToValueIdMap.end()) {
  2806. GUIDToValueIdMap[RI] = ++GlobalValueId;
  2807. RefId = GlobalValueId;
  2808. } else {
  2809. RefId = VMI->second;
  2810. }
  2811. NameVals.push_back(RefId);
  2812. }
  2813. bool HasProfileData = false;
  2814. for (auto &EI : FS->calls()) {
  2815. HasProfileData |= EI.second.ProfileCount != 0;
  2816. if (HasProfileData)
  2817. break;
  2818. }
  2819. for (auto &EI : FS->calls()) {
  2820. const auto &VMI = GUIDToValueIdMap.find(EI.first);
  2821. // If this GUID doesn't have an entry, it doesn't have a function
  2822. // summary and we don't need to record any calls to it.
  2823. if (VMI == GUIDToValueIdMap.end())
  2824. continue;
  2825. NameVals.push_back(VMI->second);
  2826. assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite");
  2827. NameVals.push_back(EI.second.CallsiteCount);
  2828. if (HasProfileData)
  2829. NameVals.push_back(EI.second.ProfileCount);
  2830. }
  2831. // Record the starting offset of this summary entry for use
  2832. // in the VST entry. Add the current code size since the
  2833. // reader will invoke readRecord after the abbrev id read.
  2834. FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
  2835. unsigned FSAbbrev =
  2836. (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
  2837. unsigned Code =
  2838. (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
  2839. // Emit the finished record.
  2840. Stream.EmitRecord(Code, NameVals, FSAbbrev);
  2841. NameVals.clear();
  2842. }
  2843. }
  2844. Stream.ExitBlock();
  2845. }
  2846. // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
  2847. // current llvm version, and a record for the epoch number.
  2848. static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) {
  2849. Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
  2850. // Write the "user readable" string identifying the bitcode producer
  2851. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2852. Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
  2853. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2854. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2855. auto StringAbbrev = Stream.EmitAbbrev(Abbv);
  2856. WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING,
  2857. "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream);
  2858. // Write the epoch version
  2859. Abbv = new BitCodeAbbrev();
  2860. Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
  2861. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  2862. auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
  2863. SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
  2864. Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
  2865. Stream.ExitBlock();
  2866. }
  2867. static void writeModuleHash(BitstreamWriter &Stream,
  2868. SmallVectorImpl<char> &Buffer,
  2869. size_t BlockStartPos) {
  2870. // Emit the module's hash.
  2871. // MODULE_CODE_HASH: [5*i32]
  2872. SHA1 Hasher;
  2873. Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Buffer[BlockStartPos],
  2874. Buffer.size() - BlockStartPos));
  2875. auto Hash = Hasher.result();
  2876. SmallVector<uint64_t, 20> Vals;
  2877. auto LShift = [&](unsigned char Val, unsigned Amount)
  2878. -> uint64_t { return ((uint64_t)Val) << Amount; };
  2879. for (int Pos = 0; Pos < 20; Pos += 4) {
  2880. uint32_t SubHash = LShift(Hash[Pos + 0], 24);
  2881. SubHash |= LShift(Hash[Pos + 1], 16) | LShift(Hash[Pos + 2], 8) |
  2882. (unsigned)(unsigned char)Hash[Pos + 3];
  2883. Vals.push_back(SubHash);
  2884. }
  2885. // Emit the finished record.
  2886. Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
  2887. }
  2888. /// WriteModule - Emit the specified module to the bitstream.
  2889. static void WriteModule(const Module *M, BitstreamWriter &Stream,
  2890. bool ShouldPreserveUseListOrder,
  2891. uint64_t BitcodeStartBit, bool EmitSummaryIndex,
  2892. bool GenerateHash, SmallVectorImpl<char> &Buffer) {
  2893. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  2894. size_t BlockStartPos = Buffer.size();
  2895. SmallVector<unsigned, 1> Vals;
  2896. unsigned CurVersion = 1;
  2897. Vals.push_back(CurVersion);
  2898. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
  2899. // Analyze the module, enumerating globals, functions, etc.
  2900. ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
  2901. // Emit blockinfo, which defines the standard abbreviations etc.
  2902. WriteBlockInfo(VE, Stream);
  2903. // Emit information about attribute groups.
  2904. WriteAttributeGroupTable(VE, Stream);
  2905. // Emit information about parameter attributes.
  2906. WriteAttributeTable(VE, Stream);
  2907. // Emit information describing all of the types in the module.
  2908. WriteTypeTable(VE, Stream);
  2909. writeComdats(VE, Stream);
  2910. // Emit top-level description of module, including target triple, inline asm,
  2911. // descriptors for global variables, and function prototype info.
  2912. uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
  2913. // Emit constants.
  2914. WriteModuleConstants(VE, Stream);
  2915. // Emit metadata.
  2916. writeModuleMetadata(*M, VE, Stream);
  2917. // Emit metadata.
  2918. WriteModuleMetadataStore(M, Stream);
  2919. // Emit module-level use-lists.
  2920. if (VE.shouldPreserveUseListOrder())
  2921. WriteUseListBlock(nullptr, VE, Stream);
  2922. WriteOperandBundleTags(M, Stream);
  2923. // Emit function bodies.
  2924. DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> FunctionIndex;
  2925. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
  2926. if (!F->isDeclaration())
  2927. WriteFunction(*F, M, VE, Stream, FunctionIndex, EmitSummaryIndex);
  2928. // Need to write after the above call to WriteFunction which populates
  2929. // the summary information in the index.
  2930. if (EmitSummaryIndex)
  2931. WritePerModuleGlobalValueSummary(FunctionIndex, M, VE, Stream);
  2932. WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
  2933. VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
  2934. if (GenerateHash) {
  2935. writeModuleHash(Stream, Buffer, BlockStartPos);
  2936. }
  2937. Stream.ExitBlock();
  2938. }
  2939. /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
  2940. /// header and trailer to make it compatible with the system archiver. To do
  2941. /// this we emit the following header, and then emit a trailer that pads the
  2942. /// file out to be a multiple of 16 bytes.
  2943. ///
  2944. /// struct bc_header {
  2945. /// uint32_t Magic; // 0x0B17C0DE
  2946. /// uint32_t Version; // Version, currently always 0.
  2947. /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
  2948. /// uint32_t BitcodeSize; // Size of traditional bitcode file.
  2949. /// uint32_t CPUType; // CPU specifier.
  2950. /// ... potentially more later ...
  2951. /// };
  2952. static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
  2953. uint32_t &Position) {
  2954. support::endian::write32le(&Buffer[Position], Value);
  2955. Position += 4;
  2956. }
  2957. static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
  2958. const Triple &TT) {
  2959. unsigned CPUType = ~0U;
  2960. // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
  2961. // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
  2962. // number from /usr/include/mach/machine.h. It is ok to reproduce the
  2963. // specific constants here because they are implicitly part of the Darwin ABI.
  2964. enum {
  2965. DARWIN_CPU_ARCH_ABI64 = 0x01000000,
  2966. DARWIN_CPU_TYPE_X86 = 7,
  2967. DARWIN_CPU_TYPE_ARM = 12,
  2968. DARWIN_CPU_TYPE_POWERPC = 18
  2969. };
  2970. Triple::ArchType Arch = TT.getArch();
  2971. if (Arch == Triple::x86_64)
  2972. CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
  2973. else if (Arch == Triple::x86)
  2974. CPUType = DARWIN_CPU_TYPE_X86;
  2975. else if (Arch == Triple::ppc)
  2976. CPUType = DARWIN_CPU_TYPE_POWERPC;
  2977. else if (Arch == Triple::ppc64)
  2978. CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
  2979. else if (Arch == Triple::arm || Arch == Triple::thumb)
  2980. CPUType = DARWIN_CPU_TYPE_ARM;
  2981. // Traditional Bitcode starts after header.
  2982. assert(Buffer.size() >= BWH_HeaderSize &&
  2983. "Expected header size to be reserved");
  2984. unsigned BCOffset = BWH_HeaderSize;
  2985. unsigned BCSize = Buffer.size() - BWH_HeaderSize;
  2986. // Write the magic and version.
  2987. unsigned Position = 0;
  2988. WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
  2989. WriteInt32ToBuffer(0 , Buffer, Position); // Version.
  2990. WriteInt32ToBuffer(BCOffset , Buffer, Position);
  2991. WriteInt32ToBuffer(BCSize , Buffer, Position);
  2992. WriteInt32ToBuffer(CPUType , Buffer, Position);
  2993. // If the file is not a multiple of 16 bytes, insert dummy padding.
  2994. while (Buffer.size() & 15)
  2995. Buffer.push_back(0);
  2996. }
  2997. /// Helper to write the header common to all bitcode files.
  2998. static void WriteBitcodeHeader(BitstreamWriter &Stream) {
  2999. // Emit the file header.
  3000. Stream.Emit((unsigned)'B', 8);
  3001. Stream.Emit((unsigned)'C', 8);
  3002. Stream.Emit(0x0, 4);
  3003. Stream.Emit(0xC, 4);
  3004. Stream.Emit(0xE, 4);
  3005. Stream.Emit(0xD, 4);
  3006. }
  3007. /// WriteBitcodeToFile - Write the specified module to the specified output
  3008. /// stream.
  3009. void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
  3010. bool ShouldPreserveUseListOrder,
  3011. bool EmitSummaryIndex, bool GenerateHash) {
  3012. SmallVector<char, 0> Buffer;
  3013. Buffer.reserve(256*1024);
  3014. // If this is darwin or another generic macho target, reserve space for the
  3015. // header.
  3016. Triple TT(M->getTargetTriple());
  3017. if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
  3018. Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
  3019. // Emit the module into the buffer.
  3020. {
  3021. BitstreamWriter Stream(Buffer);
  3022. // Save the start bit of the actual bitcode, in case there is space
  3023. // saved at the start for the darwin header above. The reader stream
  3024. // will start at the bitcode, and we need the offset of the VST
  3025. // to line up.
  3026. uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
  3027. // Emit the file header.
  3028. WriteBitcodeHeader(Stream);
  3029. WriteIdentificationBlock(M, Stream);
  3030. // Emit the module.
  3031. WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit,
  3032. EmitSummaryIndex, GenerateHash, Buffer);
  3033. }
  3034. if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
  3035. EmitDarwinBCHeaderAndTrailer(Buffer, TT);
  3036. // Write the generated bitstream to "Out".
  3037. Out.write((char*)&Buffer.front(), Buffer.size());
  3038. }
  3039. // Write the specified module summary index to the given raw output stream,
  3040. // where it will be written in a new bitcode block. This is used when
  3041. // writing the combined index file for ThinLTO.
  3042. void llvm::WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out) {
  3043. SmallVector<char, 0> Buffer;
  3044. Buffer.reserve(256 * 1024);
  3045. BitstreamWriter Stream(Buffer);
  3046. // Emit the bitcode header.
  3047. WriteBitcodeHeader(Stream);
  3048. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  3049. SmallVector<unsigned, 1> Vals;
  3050. unsigned CurVersion = 1;
  3051. Vals.push_back(CurVersion);
  3052. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
  3053. // If we have a VST, write the VSTOFFSET record placeholder and record
  3054. // its offset.
  3055. uint64_t VSTOffsetPlaceholder = WriteValueSymbolTableForwardDecl(Stream);
  3056. // Write the module paths in the combined index.
  3057. WriteModStrings(Index, Stream);
  3058. // Assign unique value ids to all functions in the index for use
  3059. // in writing out the call graph edges. Save the mapping from GUID
  3060. // to the new global value id to use when writing those edges, which
  3061. // are currently saved in the index in terms of GUID.
  3062. std::map<uint64_t, unsigned> GUIDToValueIdMap;
  3063. unsigned GlobalValueId = 0;
  3064. for (auto &II : Index)
  3065. GUIDToValueIdMap[II.first] = ++GlobalValueId;
  3066. // Write the summary combined index records.
  3067. WriteCombinedGlobalValueSummary(Index, Stream, GUIDToValueIdMap,
  3068. GlobalValueId);
  3069. // Need a special VST writer for the combined index (we don't have a
  3070. // real VST and real values when this is invoked).
  3071. WriteCombinedValueSymbolTable(Index, Stream, GUIDToValueIdMap,
  3072. VSTOffsetPlaceholder);
  3073. Stream.ExitBlock();
  3074. Out.write((char *)&Buffer.front(), Buffer.size());
  3075. }