Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(3)

Side by Side Diff: tools/pnacl-bccompress/pnacl-bccompress.cpp

Issue 154603002: Make pnacl-bccompress add abbreviations for obvious constants. (Closed) Base URL: http://git.chromium.org/native_client/pnacl-llvm.git@master
Patch Set: Fix issues raised in Patch Set 1 and 2. Created 6 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 //===-- pnacl-bccompress.cpp - Bitcode (abbrev) compression ---------------===// 1 //===-- pnacl-bccompress.cpp - Bitcode (abbrev) compression ---------------===//
2 // 2 //
3 // The LLVM Compiler Infrastructure 3 // The LLVM Compiler Infrastructure
4 // 4 //
5 // This file is distributed under the University of Illinois Open Source 5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details. 6 // License. See LICENSE.TXT for details.
7 // 7 //
8 //===----------------------------------------------------------------------===// 8 //===----------------------------------------------------------------------===//
9 // 9 //
10 // This tool may be invoked in the following manner: 10 // This tool may be invoked in the following manner:
(...skipping 82 matching lines...) Expand 10 before | Expand all | Expand 10 after
93 cl::desc("Show collected value distributions in bitcode records."), 93 cl::desc("Show collected value distributions in bitcode records."),
94 cl::init(false)); 94 cl::init(false));
95 95
96 /// Error - All bitcode analysis errors go through this function, 96 /// Error - All bitcode analysis errors go through this function,
97 /// making this a good place to breakpoint if debugging. 97 /// making this a good place to breakpoint if debugging.
98 static bool Error(const std::string &Err) { 98 static bool Error(const std::string &Err) {
99 errs() << Err << "\n"; 99 errs() << Err << "\n";
100 return true; 100 return true;
101 } 101 }
102 102
103 // For debugging. Prints out the abbreviation in readable form to errs(). 103 // Prints out the abbreviation in readable form to the given Stream.
104 static void PrintAbbrev(unsigned BlockID, const NaClBitCodeAbbrev *Abbrev) { 104 static void PrintAbbrev(raw_ostream &Stream,
105 errs() << "Abbrev(block " << BlockID << "): ["; 105 unsigned BlockID, const NaClBitCodeAbbrev *Abbrev) {
106 // ContinuationCount>0 implies that the current operand is a 106 Stream << "Abbrev(block " << BlockID << "): ";
107 // continuation of previous operand(s). 107 Abbrev->Print(Stream);
108 unsigned ContinuationCount = 0;
109 for (unsigned i = 0; i < Abbrev->getNumOperandInfos(); ++i) {
110 if (i > 0 && ContinuationCount == 0) errs() << ", ";
111 const NaClBitCodeAbbrevOp &Op = Abbrev->getOperandInfo(i);
112 if (Op.isLiteral()) {
113 errs() << Op.getLiteralValue();
114 } else if (Op.isEncoding()) {
115 switch (Op.getEncoding()) {
116 case NaClBitCodeAbbrevOp::Fixed:
117 errs() << "Fixed(" << Op.getEncodingData() << ")";
118 break;
119 case NaClBitCodeAbbrevOp::VBR:
120 errs() << "VBR(" << Op.getEncodingData() << ")";
121 break;
122 case NaClBitCodeAbbrevOp::Array:
123 errs() << "Array:";
124 ++ContinuationCount;
125 continue;
126 case NaClBitCodeAbbrevOp::Char6:
127 errs() << "Char6";
128 break;
129 case NaClBitCodeAbbrevOp::Blob:
130 errs() << "Blob";
131 break;
132 default:
133 errs() << "??";
134 break;
135 }
136 } else {
137 errs() << "??";
138 }
139 if (ContinuationCount) --ContinuationCount;
140 }
141 errs() << "]\n";
142 } 108 }
143 109
144 // Reads the input file into the given buffer. 110 // Reads the input file into the given buffer.
145 static bool ReadAndBuffer(OwningPtr<MemoryBuffer> &MemBuf) { 111 static bool ReadAndBuffer(OwningPtr<MemoryBuffer> &MemBuf) {
146 if (error_code ec = 112 if (error_code ec =
147 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), MemBuf)) { 113 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), MemBuf)) {
148 return Error("Error reading '" + InputFilename + "': " + ec.message()); 114 return Error("Error reading '" + InputFilename + "': " + ec.message());
149 } 115 }
150 116
151 if (MemBuf->getBufferSize() % 4 != 0) 117 if (MemBuf->getBufferSize() % 4 != 0)
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
208 public: 174 public:
209 // Vector to hold the (ordered) list of abbreviations. 175 // Vector to hold the (ordered) list of abbreviations.
210 typedef SmallVector<NaClBitCodeAbbrev*, 32> AbbrevVector; 176 typedef SmallVector<NaClBitCodeAbbrev*, 32> AbbrevVector;
211 177
212 BlockAbbrevs(unsigned BlockID) 178 BlockAbbrevs(unsigned BlockID)
213 : BlockID(BlockID) { 179 : BlockID(BlockID) {
214 // backfill internal indices that don't correspond to bitstream 180 // backfill internal indices that don't correspond to bitstream
215 // application abbreviations, so that added abbreviations have 181 // application abbreviations, so that added abbreviations have
216 // valid abbreviation indices. 182 // valid abbreviation indices.
217 for (unsigned i = 0; i < naclbitc::FIRST_APPLICATION_ABBREV; ++i) { 183 for (unsigned i = 0; i < naclbitc::FIRST_APPLICATION_ABBREV; ++i) {
218 Abbrevs.push_back(new NaClBitCodeAbbrev()); 184 // Make all non-application abbreviations look like the default
185 // abbreviation.
186 NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
187 Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::Array));
188 Abbrev->Add(NaClBitCodeAbbrevOp(NaClBitCodeAbbrevOp::VBR, 6));
189 Abbrevs.push_back(Abbrev);
219 } 190 }
220 GlobalAbbrevBitstreamToInternalMap. 191 GlobalAbbrevBitstreamToInternalMap.
221 SetNextBitstreamAbbrevIndex(Abbrevs.size()); 192 SetNextBitstreamAbbrevIndex(Abbrevs.size());
222 } 193 }
223 194
224 ~BlockAbbrevs() { 195 ~BlockAbbrevs() {
225 for (AbbrevVector::const_iterator 196 for (AbbrevVector::const_iterator
226 Iter = Abbrevs.begin(), IterEnd = Abbrevs.end(); 197 Iter = Abbrevs.begin(), IterEnd = Abbrevs.end();
227 Iter != IterEnd; ++Iter) { 198 Iter != IterEnd; ++Iter) {
228 (*Iter)->dropRef(); 199 (*Iter)->dropRef();
(...skipping 27 matching lines...) Expand all
256 Abbrev->dropRef(); 227 Abbrev->dropRef();
257 return false; 228 return false;
258 } 229 }
259 230
260 // New abbreviation. Add. 231 // New abbreviation. Add.
261 Index = Abbrevs.size(); 232 Index = Abbrevs.size();
262 Abbrevs.push_back(Abbrev); 233 Abbrevs.push_back(Abbrev);
263 return true; 234 return true;
264 } 235 }
265 236
237 /// Adds the given abbreviation to the set of global abbreviations
238 /// defined for the block. Guarantees that duplicate abbreviations
239 /// are not added to the block. Note: Code takes ownership of
240 /// the given abbreviation. Returns true if new abbreviation.
241 bool AddAbbreviation(NaClBitCodeAbbrev *Abbrev) {
242 int Index;
243 return AddAbbreviation(Abbrev, Index);
244 }
245
266 /// The block ID associated with the block. 246 /// The block ID associated with the block.
267 unsigned GetBlockID() const { 247 unsigned GetBlockID() const {
268 return BlockID; 248 return BlockID;
269 } 249 }
270 250
271 /// Returns the index of the frist application abbreviation for the 251 /// Returns the index of the frist application abbreviation for the
272 /// block. 252 /// block.
273 unsigned GetFirstApplicationAbbreviation() const { 253 unsigned GetFirstApplicationAbbreviation() const {
274 return naclbitc::FIRST_APPLICATION_ABBREV; 254 return naclbitc::FIRST_APPLICATION_ABBREV;
275 } 255 }
(...skipping 134 matching lines...) Expand 10 before | Expand all | Expand 10 after
410 cast<NaClCompressBlockDistElement>( 390 cast<NaClCompressBlockDistElement>(
411 Context->BlockDist.GetElement(Record.GetBlockID())) 391 Context->BlockDist.GetElement(Record.GetBlockID()))
412 ->GetAbbrevDist().AddRecord(Record); 392 ->GetAbbrevDist().AddRecord(Record);
413 } 393 }
414 394
415 virtual void ProcessRecordAbbrev() { 395 virtual void ProcessRecordAbbrev() {
416 // Convert the local abbreviation to a corresponding global 396 // Convert the local abbreviation to a corresponding global
417 // abbreviation. 397 // abbreviation.
418 const NaClBitCodeAbbrev *Abbrev = Record.GetCursor().GetNewestAbbrev(); 398 const NaClBitCodeAbbrev *Abbrev = Record.GetCursor().GetNewestAbbrev();
419 int Index; 399 int Index;
420 AddAbbreviation(GetBlockID(), Abbrev->Copy(), Index); 400 AddAbbreviation(GetBlockID(), Abbrev->Simplify(), Index);
421 LocalAbbrevBitstreamToInternalMap.InstallNewBitstreamAbbrevIndex(Index); 401 LocalAbbrevBitstreamToInternalMap.InstallNewBitstreamAbbrevIndex(Index);
422 } 402 }
423 403
424 virtual void ExitBlockInfo() { 404 virtual void ExitBlockInfo() {
425 // Now extract out global abbreviations and put into corresponding 405 // Now extract out global abbreviations and put into corresponding
426 // block abbreviations map, so that they will be used when the 406 // block abbreviations map, so that they will be used when the
427 // bitcode is compressed. 407 // bitcode is compressed.
428 NaClBitstreamReader &Reader = Record.GetReader(); 408 NaClBitstreamReader &Reader = Record.GetReader();
429 SmallVector<unsigned, 12> BlockIDs; 409 SmallVector<unsigned, 12> BlockIDs;
430 Reader.GetBlockInfoBlockIDs(BlockIDs); 410 Reader.GetBlockInfoBlockIDs(BlockIDs);
431 for (SmallVectorImpl<unsigned>::const_iterator 411 for (SmallVectorImpl<unsigned>::const_iterator
432 IDIter = BlockIDs.begin(), IDIterEnd = BlockIDs.end(); 412 IDIter = BlockIDs.begin(), IDIterEnd = BlockIDs.end();
433 IDIter != IDIterEnd; ++IDIter) { 413 IDIter != IDIterEnd; ++IDIter) {
434 unsigned BlockID = *IDIter; 414 unsigned BlockID = *IDIter;
435 BlockAbbrevs* BlkAbbrevs = GetGlobalAbbrevs(BlockID); 415 BlockAbbrevs* BlkAbbrevs = GetGlobalAbbrevs(BlockID);
436 if (const NaClBitstreamReader::BlockInfo *Info = 416 if (const NaClBitstreamReader::BlockInfo *Info =
437 Reader.getBlockInfo(BlockID)) { 417 Reader.getBlockInfo(BlockID)) {
438 for (std::vector<NaClBitCodeAbbrev*>::const_iterator 418 for (std::vector<NaClBitCodeAbbrev*>::const_iterator
439 AbbrevIter = Info->Abbrevs.begin(), 419 AbbrevIter = Info->Abbrevs.begin(),
440 AbbrevIterEnd = Info->Abbrevs.end(); 420 AbbrevIterEnd = Info->Abbrevs.end();
441 AbbrevIter != AbbrevIterEnd; 421 AbbrevIter != AbbrevIterEnd;
442 ++AbbrevIter) { 422 ++AbbrevIter) {
443 NaClBitCodeAbbrev *Abbrev = *AbbrevIter; 423 NaClBitCodeAbbrev *Abbrev = *AbbrevIter;
444 int Index; 424 int Index;
445 AddAbbreviation(BlockID, Abbrev->Copy(), Index); 425 AddAbbreviation(BlockID, Abbrev->Simplify(), Index);
446 BlkAbbrevs->GetGlobalAbbrevBitstreamToInternalMap(). 426 BlkAbbrevs->GetGlobalAbbrevBitstreamToInternalMap().
447 InstallNewBitstreamAbbrevIndex(Index); 427 InstallNewBitstreamAbbrevIndex(Index);
448 } 428 }
449 } 429 }
450 } 430 }
451 } 431 }
452 432
453 protected: 433 protected:
454 // The context (i.e. top-level) parser. 434 // The context (i.e. top-level) parser.
455 NaClAnalyzeParser *Context; 435 NaClAnalyzeParser *Context;
(...skipping 22 matching lines...) Expand all
478 // Adds the abbreviation to the list of abbreviations for the given 458 // Adds the abbreviation to the list of abbreviations for the given
479 // block. 459 // block.
480 void AddAbbreviation(unsigned BlockID, NaClBitCodeAbbrev *Abbrev, 460 void AddAbbreviation(unsigned BlockID, NaClBitCodeAbbrev *Abbrev,
481 int &Index) { 461 int &Index) {
482 // Get block abbreviations. 462 // Get block abbreviations.
483 BlockAbbrevs* Abbrevs = GetGlobalAbbrevs(BlockID); 463 BlockAbbrevs* Abbrevs = GetGlobalAbbrevs(BlockID);
484 464
485 // Read abbreviation and add as a global abbreviation. 465 // Read abbreviation and add as a global abbreviation.
486 if (Abbrevs->AddAbbreviation(Abbrev, Index) 466 if (Abbrevs->AddAbbreviation(Abbrev, Index)
487 && TraceGeneratedAbbreviations) { 467 && TraceGeneratedAbbreviations) {
488 PrintAbbrev(BlockID, Abbrev); 468 PrintAbbrev(errs(), BlockID, Abbrev);
489 } 469 }
490 } 470 }
491 471
492 /// Finds the index to the corresponding internal block abbrevation 472 /// Finds the index to the corresponding internal block abbreviation
493 /// for the given abbreviation. 473 /// for the given abbreviation.
494 int FindAbbreviation(unsigned BlockID, const NaClBitCodeAbbrev *Abbrev) { 474 int FindAbbreviation(unsigned BlockID, const NaClBitCodeAbbrev *Abbrev) {
495 return GetGlobalAbbrevs(BlockID)->FindAbbreviation(Abbrev); 475 return GetGlobalAbbrevs(BlockID)->FindAbbreviation(Abbrev);
496 } 476 }
497 477
498 void Init() { 478 void Init() {
499 GlobalBlockAbbrevs = GetGlobalAbbrevs(GetBlockID()); 479 GlobalBlockAbbrevs = GetGlobalAbbrevs(GetBlockID());
500 LocalAbbrevBitstreamToInternalMap.SetNextBitstreamAbbrevIndex( 480 LocalAbbrevBitstreamToInternalMap.SetNextBitstreamAbbrevIndex(
501 GlobalBlockAbbrevs-> 481 GlobalBlockAbbrevs->
502 GetGlobalAbbrevBitstreamToInternalMap().GetNextBitstreamAbbrevIndex()); 482 GetGlobalAbbrevBitstreamToInternalMap().GetNextBitstreamAbbrevIndex());
503 } 483 }
504 }; 484 };
505 485
506 bool NaClAnalyzeParser::ParseBlock(unsigned BlockID) { 486 bool NaClAnalyzeParser::ParseBlock(unsigned BlockID) {
507 NaClBlockAnalyzeParser Parser(BlockID, this); 487 NaClBlockAnalyzeParser Parser(BlockID, this);
508 return Parser.ParseThisBlock(); 488 return Parser.ParseThisBlock();
509 } 489 }
510 490
491 /// Models the unrolling of an abbreviation into its sequence of
492 /// individual operators. That is, unrolling arrays to match the width
493 /// of the abbreviation.
494 ///
495 /// For example, consider the abbreviation [Array(VBR(6))]. If the
496 /// distribution map has data for records of size 3, and the
497 /// distribution map suggests that a constant 4 appears as the second
498 /// element in the record, it is nontrivial to figure out how to
499 /// encorporate this into this abbrevation. Hence, we unroll the array
500 /// (3 times) to get [VBR(6), VBR(6), VBR(6), Array(VBR(6))]. To
501 /// update the second element to match the literal 4, we only need to
502 /// replace the second element in the unrolled abbreviation resulting
503 /// in [VBR(6), Lit(4), VBR(6), Array(VBR(6))].
jvoung (off chromium) 2014/02/07 21:34:10 For records of size 3, won't the fact that the abb
Karl 2014/02/07 23:26:04 Your point is well taken. Removing the array expla
504 ///
505 /// After we have done appropriate substitutions, we can simplify the
506 /// unrolled abbreviation by calling method Restore.
507 ///
508 /// Note: We unroll in the form that best matches the distribution
509 /// map. Hence, the code is stored as a separate operator. We also
510 /// keep the array abbreviation op, for untracked elements within the
511 /// distribution maps.
512 class UnrolledAbbreviation {
513 void operator=(const UnrolledAbbreviation&) LLVM_DELETED_FUNCTION;
514 public:
515 /// Unroll the given abbreviation, assuming it has the given size
516 /// (as specified in the distribution maps).
517 UnrolledAbbreviation(NaClBitCodeAbbrev *Abbrev, unsigned Size)
518 : CodeOp(0) {
519 unsigned NextOp = 0;
520 UnrollAbbrevOp(CodeOp, Abbrev, NextOp);
521 --Size;
522 for (unsigned i = 0; i < Size; ++i) {
523 // Create slot and then fill with appropriate operator.
524 AbbrevOps.push_back(CodeOp);
525 UnrollAbbrevOp(AbbrevOps[i], Abbrev, NextOp);
526 }
527 for (; NextOp < Abbrev->getNumOperandInfos(); ++NextOp) {
528 MoreOps.push_back(Abbrev->getOperandInfo(NextOp));
529 }
530 }
531
532 explicit UnrolledAbbreviation(const UnrolledAbbreviation &Abbrev)
533 : CodeOp(Abbrev.CodeOp),
534 AbbrevOps(Abbrev.AbbrevOps),
535 MoreOps(Abbrev.MoreOps) {
536 }
537
538 /// Prints out the abbreviation modeled by the unrolled
539 /// abbreviation.
540 void Print(raw_ostream &Stream) const {
541 NaClBitCodeAbbrev *Abbrev = Restore();
542 Abbrev->Print(Stream);
543 Abbrev->dropRef();
544 }
545
546 /// Converts the unrolled abbreviation back into a regular
547 /// abbreviation.
548 NaClBitCodeAbbrev *Restore() const {
549 NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
550 Abbrev->Add(CodeOp);
551 for (std::vector<NaClBitCodeAbbrevOp>::const_iterator
552 Iter = AbbrevOps.begin(), IterEnd = AbbrevOps.end();
553 Iter != IterEnd; ++Iter) {
554 Abbrev->Add(*Iter);
555 }
556 for (std::vector<NaClBitCodeAbbrevOp>::const_iterator
557 Iter = MoreOps.begin(), IterEnd = MoreOps.end();
558 Iter != IterEnd; ++Iter) {
559 Abbrev->Add(*Iter);
560 }
561 NaClBitCodeAbbrev *SimpAbbrev = Abbrev->Simplify();
562 Abbrev->dropRef();
563 return SimpAbbrev;
564 }
565
566 // The abbreviation used for the record code.
567 NaClBitCodeAbbrevOp CodeOp;
568
569 // The abbreviations used for each tracked value index.
570 std::vector<NaClBitCodeAbbrevOp> AbbrevOps;
571
572 private:
573 // Any remaining abbreviation operators not part of the unrolling.
574 std::vector<NaClBitCodeAbbrevOp> MoreOps;
575
576 // Extracts out the next abbreviation operator from the abbreviation
577 // Abbrev, given the index NextOp, and assigns it to AbbrevOp
578 void UnrollAbbrevOp(NaClBitCodeAbbrevOp &AbbrevOp,
579 NaClBitCodeAbbrev *Abbrev,
580 unsigned &NextOp) {
581 assert(NextOp < Abbrev->getNumOperandInfos());
582 const NaClBitCodeAbbrevOp &Op = Abbrev->getOperandInfo(NextOp);
583 if (Op.isEncoding() && Op.getEncoding() == NaClBitCodeAbbrevOp::Array) {
584 // Do not advance. The array operator assumes that all remaining
585 // elements should match its argument.
586 AbbrevOp = Abbrev->getOperandInfo(NextOp+1);
587 } else {
588 AbbrevOp = Op;
589 NextOp++;
590 }
591 }
592 };
593
594 /// Models a candidate block abbreviation, which is a blockID, and the
595 /// corresponding abbreviation to be considered for addition. Note:
596 /// Constructors and assignment take ownership of the abbreviation.
597 class CandBlockAbbrev {
598 public:
599 CandBlockAbbrev(unsigned BlockID, NaClBitCodeAbbrev *Abbrev)
600 : BlockID(BlockID), Abbrev(Abbrev) {
601 }
602
603 CandBlockAbbrev(const CandBlockAbbrev &BlockAbbrev)
604 : BlockID(BlockAbbrev.BlockID),
605 Abbrev(BlockAbbrev.Abbrev) {
606 Abbrev->addRef();
607 }
608
609 void operator=(const CandBlockAbbrev &BlockAbbrev) {
610 Abbrev->dropRef();
611 BlockID = BlockAbbrev.BlockID;
612 Abbrev = BlockAbbrev.Abbrev;
613 Abbrev->addRef();
614 }
615
616 ~CandBlockAbbrev() {
617 Abbrev->dropRef();
618 }
619
620 /// The block ID of the candidate abbreviation.
621 unsigned GetBlockID() const {
622 return BlockID;
623 }
624
625 /// The abbreviation of the candidate abbreviation.
626 const NaClBitCodeAbbrev *GetAbbrev() const {
627 return Abbrev;
628 }
629
630 /// orders this against the candidate abbreviation.
631 int Compare(const CandBlockAbbrev &CandAbbrev) const {
632 unsigned diff = BlockID - CandAbbrev.BlockID;
633 if (diff) return diff;
634 return Abbrev->Compare(*CandAbbrev.Abbrev);
635 }
636
637 /// Prints the candidate abbreviation to the given stream.
638 void Print(raw_ostream &Stream) const {
639 PrintAbbrev(Stream, BlockID, Abbrev);
640 }
641
642 private:
643 // The block the abbreviation applies to.
644 unsigned BlockID;
645 // The candidate abbreviation.
646 NaClBitCodeAbbrev *Abbrev;
647 };
648
649 static inline bool operator<(const CandBlockAbbrev &A1,
650 const CandBlockAbbrev &A2) {
651 return A1.Compare(A2) < 0;
652 }
653
654 /// Models the minimum number of instances for a candidate abbreviation
655 /// before we will even consider it a potential candidate abbreviation.
656 static unsigned MinNumInstancesForNewAbbrevs = 100;
657
658 /// Models the set of candidate abbreviations being considered, and
659 /// the number of abbreviations associated with each candidate
660 /// Abbreviation.
661 ///
662 /// Note: Because we may have abbreviation refinements of A->B->C and
663 /// A->D->C, we need to accumulate instance counts in such cases.
664 class CandidateAbbrevs {
665 public:
666 // Map from candidate abbreviations to the corresponding number of
667 // instances.
668 typedef std::map<CandBlockAbbrev, unsigned> AbbrevCountMap;
669 typedef AbbrevCountMap::const_iterator const_iterator;
670
671 /// Creates an empty set of candidate abbreviations, to be
672 /// (potentially) added to the given set of block abbreviations.
673 /// Argument is the (global) block abbreviations map, which is
674 /// used to determine if it already exists.
675 CandidateAbbrevs(BlockAbbrevsMapType &BlockAbbrevsMap)
676 : BlockAbbrevsMap(BlockAbbrevsMap)
677 {}
678
679 /// Adds the given (unrolled) abbreviation as a candidate
680 /// abbreviation to the given block. NumInstances is the number of
681 /// instances expected to use this candidate abbreviation. Returns
682 /// true if the corresponding candidate abbreviation is added to this
683 /// set of candidate abbreviations.
684 bool Add(unsigned BlockID,
685 UnrolledAbbreviation &UnrolledAbbrev,
686 unsigned NumInstances);
687
688 /// Returns the list of candidate abbreviations in this set.
689 const AbbrevCountMap &GetAbbrevsMap() const {
690 return AbbrevsMap;
691 }
692
693 /// Prints out the current contents of this set.
694 void Print(raw_ostream &Stream, const char *Title = "Candidates") const {
695 Stream << "-- " << Title << ": \n";
696 for (const_iterator Iter = AbbrevsMap.begin(), IterEnd = AbbrevsMap.end();
697 Iter != IterEnd; ++Iter) {
698 Stream << format("%12u", Iter->second) << ": ";
699 Iter->first.Print(Stream);
700 }
701 Stream << "--\n";
702 }
703
704 private:
705 // The set of abbreviations and corresponding number instances.
706 AbbrevCountMap AbbrevsMap;
707
708 // The map of (global) abbreviations already associated with each block.
709 BlockAbbrevsMapType &BlockAbbrevsMap;
710 };
711
712 bool CandidateAbbrevs::Add(unsigned BlockID,
713 UnrolledAbbreviation &UnrolledAbbrev,
714 unsigned NumInstances) {
715 // Drop if it corresponds to an existing global abbreviation.
716 NaClBitCodeAbbrev *Abbrev = UnrolledAbbrev.Restore();
717 if (BlockAbbrevs* Abbrevs = BlockAbbrevsMap[BlockID]) {
718 if (Abbrevs->FindAbbreviation(Abbrev) !=
719 BlockAbbrevs::NO_SUCH_ABBREVIATION) {
720 Abbrev->dropRef();
721 return false;
722 }
723 }
724
725 CandBlockAbbrev CandAbbrev(BlockID, Abbrev);
726 AbbrevCountMap::iterator Pos = AbbrevsMap.find(CandAbbrev);
727 if (Pos == AbbrevsMap.end()) {
728 AbbrevsMap[CandAbbrev] = NumInstances;
729 } else {
730 Pos->second += NumInstances;
731 }
732 return true;
733 }
734
735 // Look for new abbreviations in block BlockID, considering it was
736 // read with the given abbreviation Abbrev, and considering changing
737 // the abbreviation opererator for value Index. ValueDist is how
738 // values at Index are distributed. Any found abbreviations are added
739 // to the candidate abbreviations CandAbbrevs. Returns true only if we
740 // have added new candidate abbreviations to CandAbbrevs.
741 static bool AddNewAbbreviations(unsigned BlockID,
742 const UnrolledAbbreviation &Abbrev,
743 unsigned Index,
744 NaClBitcodeValueDist &ValueDist,
745 CandidateAbbrevs &CandAbbrevs) {
746 // TODO(kschimpf): Add code to try and find a better encoding for
747 // the values, based on the distribution.
748
749 // If this index is already a literal abbreviation, no improvements can
750 // be made.
751 const NaClBitCodeAbbrevOp Op = Abbrev.AbbrevOps[Index];
752 if (Op.isLiteral()) return false;
753
754 // Search based on sorted distribution, which sorts by number of
755 // instances. Start by trying to find possible constants to use.
756 const NaClBitcodeDist::Distribution *
757 Distribution = ValueDist.GetDistribution();
758 for (NaClBitcodeDist::Distribution::const_iterator
759 Iter = Distribution->begin(), IterEnd = Distribution->end();
760 Iter != IterEnd; ++Iter) {
761 NaClValueRangeType Range = GetNaClValueRange(Iter->second);
762 if (Range.first != Range.second) continue; // not a constant.
763
764 // Defines a constant. Try as new candidate range. In addition,
765 // don't try any more constant values, since this is the one with
766 // the greatest number of instances.
767 NaClBitcodeDistElement *Elmt = ValueDist.at(Range.first);
768 UnrolledAbbreviation CandAbbrev(Abbrev);
769 CandAbbrev.AbbrevOps[Index] = NaClBitCodeAbbrevOp(Range.first);
770 return CandAbbrevs.Add(BlockID, CandAbbrev, Elmt->GetNumInstances());
771 }
772 return false;
773 }
774
775 // Look for new abbreviations in block BlockID, considering it was
776 // read with the given abbreviation Abbrev. IndexDist is the
777 // corresponding distribution of value indices associated with the
778 // abbreviation. Any found abbreviations are added to the candidate
779 // abbreviations CandAbbrevs.
780 static void AddNewAbbreviations(unsigned BlockID,
781 const UnrolledAbbreviation &Abbrev,
782 NaClBitcodeDist &IndexDist,
783 CandidateAbbrevs &CandAbbrevs) {
784 // Search based on sorted distribution, which sorts based on heuristic
785 // of best index to fix first.
786 const NaClBitcodeDist::Distribution *
787 IndexDistribution = IndexDist.GetDistribution();
788 for (NaClBitcodeDist::Distribution::const_iterator
789 IndexIter = IndexDistribution->begin(),
790 IndexIterEnd = IndexDistribution->end();
791 IndexIter != IndexIterEnd; ++IndexIter) {
792 unsigned Index = static_cast<unsigned>(IndexIter->second);
793 if (AddNewAbbreviations(
794 BlockID, Abbrev, Index,
795 cast<NaClBitcodeValueIndexDistElement>(IndexDist.at(Index))
796 ->GetValueDist(),
797 CandAbbrevs)) {
798 return;
799 }
800 }
801 }
802
803 // Look for new abbreviations in block BlockID, considering it was
804 // read with the given abbreviation Abbrev, and the given record Code.
805 // SizeDist is the corresponding distribution of sizes associated with
806 // the abbreviation. Any found abbreviations are added to the
807 // candidate abbreviations CandAbbrevs.
808 static void AddNewAbbreviations(unsigned BlockID,
809 NaClBitCodeAbbrev *Abbrev,
810 unsigned Code,
811 NaClBitcodeDist &SizeDist,
812 CandidateAbbrevs &CandAbbrevs) {
813 const NaClBitcodeDist::Distribution *
814 SizeDistribution = SizeDist.GetDistribution();
815 for (NaClBitcodeDist::Distribution::const_iterator
816 SizeIter = SizeDistribution->begin(),
817 SizeIterEnd = SizeDistribution->end();
818 SizeIter != SizeIterEnd; ++SizeIter) {
819 unsigned Size = static_cast<unsigned>(SizeIter->second);
820 UnrolledAbbreviation UnrolledAbbrev(Abbrev, Size+1); // Add code!
821 if (!UnrolledAbbrev.CodeOp.isLiteral()) {
822 // Try making the code a literal.
823 UnrolledAbbreviation CandAbbrev(UnrolledAbbrev);
824 CandAbbrev.CodeOp = NaClBitCodeAbbrevOp(Code);
825 CandAbbrevs.Add(BlockID, CandAbbrev,
826 SizeDist.at(Size)->GetNumInstances());
827 }
828 // Now process value indices to find candidate abbreviations.
829 AddNewAbbreviations(
830 BlockID, UnrolledAbbrev,
831 cast<NaClBitcodeSizeDistElement>(SizeDist.at(Size))
832 ->GetValueIndexDist(),
833 CandAbbrevs);
834 }
835 }
836
837 // Look for new abbreviations in block BlockID. Abbrevs is the map of
838 // read (globally defined) abbreviations associated with the
839 // BlockID. AbbrevDist is the distribution map of abbreviations
840 // associated with BlockID. Any found abbreviations are added to the
841 // candidate abbreviations CandAbbrevs.
842 static void AddNewAbbreviations(unsigned BlockID,
843 BlockAbbrevs *Abbrevs,
844 NaClBitcodeDist &AbbrevDist,
845 CandidateAbbrevs &CandAbbrevs) {
846 const NaClBitcodeDist::Distribution *
847 AbbrevDistribution = AbbrevDist.GetDistribution();
848 for (NaClBitcodeDist::Distribution::const_iterator
849 AbbrevIter = AbbrevDistribution->begin(),
850 AbbrevIterEnd = AbbrevDistribution->end();
851 AbbrevIter != AbbrevIterEnd; ++AbbrevIter) {
852 NaClBitcodeDistValue AbbrevIndex = AbbrevIter->second;
853 NaClBitCodeAbbrev *Abbrev = Abbrevs->GetIndexedAbbrev(AbbrevIndex);
854 NaClBitcodeAbbrevDistElement *AbbrevElmt =
855 cast<NaClBitcodeAbbrevDistElement>(AbbrevDist.at(AbbrevIndex));
856 NaClBitcodeDist &CodeDist = AbbrevElmt->GetCodeDist();
857
858 const NaClBitcodeDist::Distribution *
859 CodeDistribution = CodeDist.GetDistribution();
860 for (NaClBitcodeDist::Distribution::const_iterator
861 CodeIter = CodeDistribution->begin(),
862 CodeIterEnd = CodeDistribution->end();
863 CodeIter != CodeIterEnd; ++CodeIter) {
864 unsigned Code = static_cast<unsigned>(CodeIter->second);
865 AddNewAbbreviations(
866 BlockID,
867 Abbrev,
868 Code,
869 cast<NaClCompressCodeDistElement>(CodeDist.at(CodeIter->second))
870 ->GetSizeDist(),
871 CandAbbrevs);
872 }
873 }
874 }
875
876 typedef std::pair<unsigned, CandBlockAbbrev> CountedAbbrevType;
877
878 // Look for new abbreviations in the given block distribution map
879 // BlockDist. BlockAbbrevsMap contains the set of read global
880 // abbreviations. Adds found candidate abbreviations to the set of
881 // known global abbreviations.
882 static void AddNewAbbreviations(NaClBitcodeBlockDist &BlockDist,
883 BlockAbbrevsMapType &BlockAbbrevsMap) {
884 CandidateAbbrevs CandAbbrevs(BlockAbbrevsMap);
885 // Start by collecting candidate abbreviations.
886 const NaClBitcodeDist::Distribution *
887 Distribution = BlockDist.GetDistribution();
888 for (NaClBitcodeDist::Distribution::const_iterator
889 Iter = Distribution->begin(), IterEnd = Distribution->end();
890 Iter != IterEnd; ++Iter) {
891 unsigned BlockID = static_cast<unsigned>(Iter->second);
892 AddNewAbbreviations(
893 BlockID,
894 BlockAbbrevsMap[BlockID],
895 cast<NaClCompressBlockDistElement>(BlockDist.at(BlockID))
896 ->GetAbbrevDist(),
897 CandAbbrevs);
898 }
899 // Install candidate abbreviations.
900 //
901 // Sort the candidate abbreviations by number of instances, so that
902 // if multiple abbreviations apply, the one with the largest number
903 // of instances will be chosen when generating compressed file.
jvoung (off chromium) 2014/02/07 21:34:10 "when compressing a file"
Karl 2014/02/07 23:26:04 Done.
904 //
905 // For example, we may have just generated two abbreviations. The
906 // first has replaced the 3rd element with the constant 4 while the
907 // second replaced the 4th element with the constant 5. The first
908 // abbreviation can apply to 300 records while the second can apply
909 // to 1000 records. Assuming that both abbreviations shrink the
910 // record by the same number of bits, we clearly want the tool to
911 // choose the second abbreviation when selecting the abbreviation
912 // index to choose (via method GetRecordAbbrevIndex).
913 //
914 // Selecting the second is important in that abbreviation are
915 // refined by successive calls to this tool. We do not want to
916 // restrict downstream refinements prematurely. Hence, we want the
917 // tool to choose the abbreviation with the most candidates first.
918 //
919 // Since method GetRecordAbbrevIndex chooses the first abbreviation
920 // that generates the least number of bits, we clearly want to make
921 // sure that the second abbreviation occurs before the first.
922 std::vector<CountedAbbrevType> Candidates;
923 for (CandidateAbbrevs::const_iterator
924 Iter = CandAbbrevs.GetAbbrevsMap().begin(),
925 IterEnd = CandAbbrevs.GetAbbrevsMap().end();
926 Iter != IterEnd; ++Iter) {
927 Candidates.push_back(CountedAbbrevType(Iter->second,Iter->first));
928 }
929 std::sort(Candidates.begin(), Candidates.end());
930 std::vector<CountedAbbrevType>::const_reverse_iterator
931 Iter = Candidates.rbegin(), IterEnd = Candidates.rend();
932 if (Iter == IterEnd) return;
933
934 if (TraceGeneratedAbbreviations) {
935 errs() << "-- New abbrevations:\n";
936 }
937 unsigned Min = (Iter->first >> 2);
938 for (; Iter != IterEnd; ++Iter) {
939 if (Iter->first < Min) break;
940 unsigned BlockID = Iter->second.GetBlockID();
941 BlockAbbrevs *Abbrevs = BlockAbbrevsMap[BlockID];
942 NaClBitCodeAbbrev *Abbrev = Iter->second.GetAbbrev()->Copy();
943 if (TraceGeneratedAbbreviations) {
944 errs() <<format("%12u", Iter->first) << ": ";
945 PrintAbbrev(errs(), BlockID, Abbrev);
946 }
947 Abbrevs->AddAbbreviation(Abbrev);
948 }
949 errs() << "--\n";
jvoung (off chromium) 2014/02/07 21:34:10 if (TraceGeneratedAbbreviations) ?
Karl 2014/02/07 23:26:04 Done.
950 }
951
511 // Read in bitcode, analyze data, and figure out set of abbreviations 952 // Read in bitcode, analyze data, and figure out set of abbreviations
512 // to use, from memory buffer MemBuf containing the input bitcode file. 953 // to use, from memory buffer MemBuf containing the input bitcode file.
513 static bool AnalyzeBitcode(OwningPtr<MemoryBuffer> &MemBuf, 954 static bool AnalyzeBitcode(OwningPtr<MemoryBuffer> &MemBuf,
514 BlockAbbrevsMapType &BlockAbbrevsMap) { 955 BlockAbbrevsMapType &BlockAbbrevsMap) {
515 // TODO(kschimpf): The current code only extracts abbreviations 956 // TODO(kschimpf): The current code only extracts abbreviations
516 // defined in the bitcode file. This code needs to be updated to 957 // defined in the bitcode file. This code needs to be updated to
517 // collect data distributions and figure out better (global) 958 // collect data distributions and figure out better (global)
518 // abbreviations to use. 959 // abbreviations to use.
519 960
520 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart(); 961 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
(...skipping 14 matching lines...) Expand all
535 if (Parser.Parse()) return true; 976 if (Parser.Parse()) return true;
536 } 977 }
537 978
538 if (ShowValueDistributions) { 979 if (ShowValueDistributions) {
539 // To make shell redirection of this trace easier, print it to 980 // To make shell redirection of this trace easier, print it to
540 // stdout unless stdout is being used to contain the compressed 981 // stdout unless stdout is being used to contain the compressed
541 // bitcode file. In the latter case, use stderr. 982 // bitcode file. In the latter case, use stderr.
542 Parser.BlockDist.Print(OutputFilename == "-" ? errs() : outs()); 983 Parser.BlockDist.Print(OutputFilename == "-" ? errs() : outs());
543 } 984 }
544 985
986 AddNewAbbreviations(Parser.BlockDist, BlockAbbrevsMap);
545 return false; 987 return false;
546 } 988 }
547 989
548 /// Parses the input bitcode file and generates the corresponding 990 /// Parses the input bitcode file and generates the corresponding
549 /// compressed bitcode file, by replacing abbreviations in the input 991 /// compressed bitcode file, by replacing abbreviations in the input
550 /// file with the corresponding abbreviations defined in 992 /// file with the corresponding abbreviations defined in
551 /// BlockAbbrevsMap. 993 /// BlockAbbrevsMap.
552 class NaClBitcodeCopyParser : public NaClBitcodeParser { 994 class NaClBitcodeCopyParser : public NaClBitcodeParser {
553 public: 995 public:
554 // Top-level constructor to build the appropriate block parser 996 // Top-level constructor to build the appropriate block parser
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
616 NaClBlockCopyParser *EnclosingParser) 1058 NaClBlockCopyParser *EnclosingParser)
617 : NaClBitcodeParser(BlockID, EnclosingParser), 1059 : NaClBitcodeParser(BlockID, EnclosingParser),
618 Context(EnclosingParser->Context) 1060 Context(EnclosingParser->Context)
619 {} 1061 {}
620 1062
621 virtual bool Error(const std::string &Message) { 1063 virtual bool Error(const std::string &Message) {
622 // Use local error routine so that all errors are treated uniformly. 1064 // Use local error routine so that all errors are treated uniformly.
623 return ::Error(Message); 1065 return ::Error(Message);
624 } 1066 }
625 1067
1068 /// Returns the set of (global) block abbreviations defined for the
1069 /// given block ID.
1070 BlockAbbrevs *GetGlobalAbbrevs(unsigned BlockID) {
1071 BlockAbbrevs *Abbrevs = Context->BlockAbbrevsMap[BlockID];
1072 if (Abbrevs == 0) {
1073 Abbrevs = new BlockAbbrevs(BlockID);
1074 Context->BlockAbbrevsMap[BlockID] = Abbrevs;
1075 }
1076 return Abbrevs;
1077 }
1078
626 virtual bool ParseBlock(unsigned BlockID) { 1079 virtual bool ParseBlock(unsigned BlockID) {
627 NaClBlockCopyParser Parser(BlockID, this); 1080 NaClBlockCopyParser Parser(BlockID, this);
628 return Parser.ParseThisBlock(); 1081 return Parser.ParseThisBlock();
629 } 1082 }
630 1083
631 virtual void EnterBlock(unsigned NumWords) { 1084 virtual void EnterBlock(unsigned NumWords) {
632 unsigned BlockID = GetBlockID(); 1085 unsigned BlockID = GetBlockID();
633 BlockAbbreviations = Context->BlockAbbrevsMap[BlockID]; 1086 BlockAbbreviations = GetGlobalAbbrevs(BlockID);
634 1087
635 // Enter the subblock. 1088 // Enter the subblock.
636 NaClBitcodeSelectorAbbrev 1089 NaClBitcodeSelectorAbbrev
637 Selector(BlockAbbreviations->GetNumberAbbreviations()-1); 1090 Selector(BlockAbbreviations->GetNumberAbbreviations()-1);
638 Context->Writer.EnterSubblock(BlockID, Selector); 1091 Context->Writer.EnterSubblock(BlockID, Selector);
1092
1093 // Note: We must dump module abbreviations as local
1094 // abbreviations, because they are in a yet to be
1095 // dumped BlockInfoBlock.
1096 if (BlockID == naclbitc::MODULE_BLOCK_ID) {
1097 BlockAbbrevs* Abbrevs = GetGlobalAbbrevs(naclbitc::MODULE_BLOCK_ID);
1098 for (unsigned i = 0; i < Abbrevs->GetNumberAbbreviations(); ++i) {
1099 Context->Writer.EmitAbbrev(Abbrevs->GetIndexedAbbrev(i)->Copy());
1100 }
1101 }
639 } 1102 }
640 1103
641 virtual void ExitBlock() { 1104 virtual void ExitBlock() {
642 Context->Writer.ExitBlock(); 1105 Context->Writer.ExitBlock();
643 } 1106 }
644 1107
645 virtual void ExitBlockInfo() { 1108 virtual void ExitBlockInfo() {
646 assert(!Context->FoundFirstBlockInfo && 1109 assert(!Context->FoundFirstBlockInfo &&
647 "Input bitcode has more that one BlockInfoBlock"); 1110 "Input bitcode has more that one BlockInfoBlock");
648 Context->FoundFirstBlockInfo = true; 1111 Context->FoundFirstBlockInfo = true;
649 1112
650 // Generate global abbreviations within a blockinfo block. 1113 // Generate global abbreviations within a blockinfo block.
651 Context->Writer.EnterBlockInfoBlock(); 1114 Context->Writer.EnterBlockInfoBlock();
652 for (BlockAbbrevsMapType::const_iterator 1115 for (BlockAbbrevsMapType::const_iterator
653 Iter = Context->BlockAbbrevsMap.begin(), 1116 Iter = Context->BlockAbbrevsMap.begin(),
654 IterEnd = Context->BlockAbbrevsMap.end(); 1117 IterEnd = Context->BlockAbbrevsMap.end();
655 Iter != IterEnd; ++Iter) { 1118 Iter != IterEnd; ++Iter) {
656 unsigned BlockID = Iter->first; 1119 unsigned BlockID = Iter->first;
1120 // Don't emit module abbreviations, since they have been
1121 // emitted as local abbreviations.
1122 if (BlockID == naclbitc::MODULE_BLOCK_ID) continue;
1123
657 BlockAbbrevs *Abbrevs = Iter->second; 1124 BlockAbbrevs *Abbrevs = Iter->second;
658 if (Abbrevs == 0) continue; 1125 if (Abbrevs == 0) continue;
659 for (unsigned i = Abbrevs->GetFirstApplicationAbbreviation(); 1126 for (unsigned i = Abbrevs->GetFirstApplicationAbbreviation();
660 i < Abbrevs->GetNumberAbbreviations(); ++i) { 1127 i < Abbrevs->GetNumberAbbreviations(); ++i) {
661 NaClBitCodeAbbrev *Abbrev = Abbrevs->GetIndexedAbbrev(i); 1128 NaClBitCodeAbbrev *Abbrev = Abbrevs->GetIndexedAbbrev(i);
662 Context->Writer.EmitBlockInfoAbbrev(BlockID, Abbrev); 1129 Context->Writer.EmitBlockInfoAbbrev(BlockID, Abbrev);
663 } 1130 }
664 } 1131 }
665 Context->Writer.ExitBlock(); 1132 Context->Writer.ExitBlock();
666 } 1133 }
(...skipping 281 matching lines...) Expand 10 before | Expand all | Expand 10 after
948 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 1415 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
949 cl::ParseCommandLineOptions(argc, argv, "pnacl-bccompress file analyzer\n"); 1416 cl::ParseCommandLineOptions(argc, argv, "pnacl-bccompress file analyzer\n");
950 1417
951 OwningPtr<MemoryBuffer> MemBuf; 1418 OwningPtr<MemoryBuffer> MemBuf;
952 if (ReadAndBuffer(MemBuf)) return 1; 1419 if (ReadAndBuffer(MemBuf)) return 1;
953 BlockAbbrevsMapType BlockAbbrevsMap; 1420 BlockAbbrevsMapType BlockAbbrevsMap;
954 if (AnalyzeBitcode(MemBuf, BlockAbbrevsMap)) return 1; 1421 if (AnalyzeBitcode(MemBuf, BlockAbbrevsMap)) return 1;
955 if (CopyBitcode(MemBuf, BlockAbbrevsMap)) return 1; 1422 if (CopyBitcode(MemBuf, BlockAbbrevsMap)) return 1;
956 return 0; 1423 return 0;
957 } 1424 }
OLDNEW
« lib/Bitcode/NaCl/Reader/NaClBitCodes.cpp ('K') | « lib/Bitcode/NaCl/Reader/NaClBitcodeDist.cpp ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698