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

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 for patch set 1. 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. Note: We unroll in the form that best matches
494 // the distribution map. Hence, the code is stored as a separate
495 // operator. We also keep the array abbreviation op, for untracked
496 // elements within the distribution maps.
497 class UnrolledAbbreviation {
498 void operator=(const UnrolledAbbreviation&) LLVM_DELETED_FUNCTION;
499 public:
500 /// Unroll the given abbreviation, assuming it has the given size
501 /// (as specified in the distribution maps).
502 UnrolledAbbreviation(NaClBitCodeAbbrev *Abbrev, unsigned Size)
503 : CodeOp(0) {
504 unsigned NextOp = 0;
505 UnrollAbbrevOp(CodeOp, Abbrev, NextOp);
506 --Size;
507 for (unsigned i = 0; i < Size; ++i) {
508 // Create slot and then fill with appropriate operator.
509 AbbrevOps.push_back(CodeOp);
510 UnrollAbbrevOp(AbbrevOps[i], Abbrev, NextOp);
511 }
512 for (; NextOp < Abbrev->getNumOperandInfos(); ++NextOp) {
513 MoreOps.push_back(Abbrev->getOperandInfo(NextOp));
514 }
515 }
516
517 explicit UnrolledAbbreviation(const UnrolledAbbreviation &Abbrev)
518 : CodeOp(Abbrev.CodeOp),
519 AbbrevOps(Abbrev.AbbrevOps),
520 MoreOps(Abbrev.MoreOps) {
521 }
522
523 /// Prints out the abbreviation modeled by the unrolled
524 /// abbreviation.
525 void Print(raw_ostream &Stream) const {
526 NaClBitCodeAbbrev *Abbrev = roll();
527 Abbrev->Print(Stream);
528 Abbrev->dropRef();
529 }
530
531 /// Converts the unrolled abbreviation back into a regular
532 /// abbreviation.
533 NaClBitCodeAbbrev *roll() const {
534 NaClBitCodeAbbrev *Abbrev = new NaClBitCodeAbbrev();
535 Abbrev->Add(CodeOp);
536 for (std::vector<NaClBitCodeAbbrevOp>::const_iterator
537 Iter = AbbrevOps.begin(), IterEnd = AbbrevOps.end();
538 Iter != IterEnd; ++Iter) {
539 Abbrev->Add(*Iter);
540 }
541 for (std::vector<NaClBitCodeAbbrevOp>::const_iterator
542 Iter = MoreOps.begin(), IterEnd = MoreOps.end();
543 Iter != IterEnd; ++Iter) {
544 Abbrev->Add(*Iter);
545 }
546 NaClBitCodeAbbrev *SimpAbbrev = Abbrev->Simplify();
547 Abbrev->dropRef();
548 return SimpAbbrev;
549 }
550
551 // The abbreviation used for the record code.
552 NaClBitCodeAbbrevOp CodeOp;
553
554 // The abbreviations used for each tracked value index.
555 std::vector<NaClBitCodeAbbrevOp> AbbrevOps;
556
557 private:
558 // Any remaining abbreviation operators not part of the unrolling.
559 std::vector<NaClBitCodeAbbrevOp> MoreOps;
560
561 // Extracts out the next abbreviation operator from the abbreviation
562 // Abbrev, given the index NextOp, and assigns it to AbbrevOp
563 void UnrollAbbrevOp(NaClBitCodeAbbrevOp &AbbrevOp,
564 NaClBitCodeAbbrev *Abbrev,
565 unsigned &NextOp) {
566 assert(NextOp < Abbrev->getNumOperandInfos());
567 const NaClBitCodeAbbrevOp &Op = Abbrev->getOperandInfo(NextOp);
568 if (Op.isEncoding() && Op.getEncoding() == NaClBitCodeAbbrevOp::Array) {
569 // Do not advance. The array operator assumes that all remaining
570 // elements should match its argument.
571 AbbrevOp = Abbrev->getOperandInfo(NextOp+1);
572 } else {
573 AbbrevOp = Op;
574 NextOp++;
575 }
576 }
577 };
578
579 /// Models a candidate block abbreviation, which is a blockID, the
580 /// corresponding abbreviation to be considered for addition. Note:
581 /// Constructors and assignment take ownership of the abbreviation.
582 class CandBlockAbbrev {
583 public:
584 CandBlockAbbrev(unsigned BlockID, NaClBitCodeAbbrev *Abbrev)
585 : BlockID(BlockID), Abbrev(Abbrev) {
586 }
587
588 CandBlockAbbrev(const CandBlockAbbrev &BlockAbbrev)
589 : BlockID(BlockAbbrev.BlockID),
590 Abbrev(BlockAbbrev.Abbrev) {
591 Abbrev->addRef();
592 }
593
594 void operator=(const CandBlockAbbrev &BlockAbbrev) {
595 Abbrev->dropRef();
596 BlockID = BlockAbbrev.BlockID;
597 Abbrev = BlockAbbrev.Abbrev;
598 Abbrev->addRef();
599 }
600
601 ~CandBlockAbbrev() {
602 Abbrev->dropRef();
603 }
604
605 /// The block ID of the candidate abbreviation.
606 unsigned GetBlockID() const {
607 return BlockID;
608 }
609
610 /// The abbreviation of the candidate abbreviation.
611 const NaClBitCodeAbbrev *GetAbbrev() const {
612 return Abbrev;
613 }
614
615 /// orders this against the candidate abbreviation.
616 int Compare(const CandBlockAbbrev &CandAbbrev) const {
617 unsigned diff = BlockID - CandAbbrev.BlockID;
618 if (diff) return diff;
619 return Abbrev->Compare(*CandAbbrev.Abbrev);
620 }
621
622 /// Prints the candidate abbreviation to the given stream.
623 void Print(raw_ostream &Stream) const {
624 PrintAbbrev(Stream, BlockID, Abbrev);
625 }
626
627 private:
628 // The block the abbreviation applies to.
629 unsigned BlockID;
630 // The candidate abbreviation.
631 NaClBitCodeAbbrev *Abbrev;
632 };
633
634 static inline bool operator<(const CandBlockAbbrev &A1,
635 const CandBlockAbbrev &A2) {
636 return A1.Compare(A2) < 0;
637 }
638
639 /// Models the minimum number of instances for a candidate abbreviation
640 /// before we will even consider it a potential candidate abbreviation.
641 static unsigned MinNumInstancesForNewAbbrevs = 100;
642
643 /// Models the set of candidate abbreviations being considered.
644 /// Filters based on the number of instances of each candidate
645 /// abbreviation. This filter is done to only keep candidates that
646 /// most likely will reduce bitcode size.
647 class CandidateAbbrevs {
648 public:
649 // Map from candidate abbreviations to the corresponding number of
650 // instances.
651 typedef std::map<CandBlockAbbrev, unsigned> AbbrevCountMap;
652 typedef AbbrevCountMap::const_iterator const_iterator;
653
654 /// Creates an empty set of candidate abbreviations, to be
655 /// (potentially) added to the given set of block abbreviations.
656 /// Argument is the (global) block abbreviations map, which is
657 /// used to determine if it already exists.
658 CandidateAbbrevs(BlockAbbrevsMapType &BlockAbbrevsMap)
659 : MaxInstances(0), BlockAbbrevsMap(BlockAbbrevsMap)
660 {}
661
662 /// Adds the given (unrolled) abbreviation as a candidate
663 /// abbreviation to the given block. NumInstances is the number of
664 /// instances expected to use this candidate abbreviation. Returns
665 /// true if the corresponding candidate abbreviation is added to this
666 /// set of candidate abbreviations. Note: depending on the value
667 /// of NumInstances, methods GetMaxInstances and GetMinInstances
668 /// may change to include NumInstances, if the candidate abbreviation
669 /// is added.
670 bool Add(unsigned BlockID,
671 UnrolledAbbreviation &UnrolledAbbrev,
672 unsigned NumInstances);
673
674 /// Returns the upper range (of number instances) that is currently
675 /// associated with this set of candidate abbreviations.
676 unsigned GetMaxInstances() const {
677 return MaxInstances;
678 }
679
680 /// Returns the lower range (of number instances) that is currently
681 /// associated with this set of candidate abbreviations. Note:
682 /// The current implementation is a guesstimate for chunking out the
683 /// best abbreviations.
684 unsigned GetMinInstances() const {
685 if (MaxInstances <= 1024) {
686 return 0;
687 } else
688 return MaxInstances >> 4;
689 }
690
691 /// Returns the list of candidate abbreviations in this set.
692 const AbbrevCountMap &GetAbbrevsMap() const {
693 return AbbrevsMap;
694 }
695
696 /// Prints out the current contents of this set.
697 void Print(raw_ostream &Stream, const char *Title = "Candidates") const {
698 Stream << "-- " << Title << ": \n";
699 for (const_iterator Iter = AbbrevsMap.begin(), IterEnd = AbbrevsMap.end();
700 Iter != IterEnd; ++Iter) {
701 Stream << format("%12u", Iter->second) << ": ";
702 Iter->first.Print(Stream);
703 }
704 Stream << "--\n";
705 }
706
707 private:
708 // The upper bound of instances in this set.
709 unsigned MaxInstances;
710
711 // The set of abbreviations and corresponding number instancs.
jvoung (off chromium) 2014/02/06 23:19:37 instances
Karl 2014/02/07 19:37:29 Done.
jvoung (off chromium) 2014/02/07 21:34:10 sorry missed this in last comment: number *of* ins
712 AbbrevCountMap AbbrevsMap;
713
714 // The map of (global) abbreviations already associated with each block.
715 BlockAbbrevsMapType &BlockAbbrevsMap;
716 };
717
718 bool CandidateAbbrevs::Add(unsigned BlockID,
719 UnrolledAbbreviation &UnrolledAbbrev,
720 unsigned NumInstances) {
721 // First see if we shouldn't add, because not enough instances apply.
722 if (NumInstances < MinNumInstancesForNewAbbrevs) return false;
723 if (NumInstances < GetMinInstances()) return false;
724
725 // Drop if it corresponds to an existing global abbreviation.
726 NaClBitCodeAbbrev *Abbrev = UnrolledAbbrev.roll();
727 if (BlockAbbrevs* Abbrevs = BlockAbbrevsMap[BlockID]) {
728 if (Abbrevs->FindAbbreviation(Abbrev) !=
729 BlockAbbrevs::NO_SUCH_ABBREVIATION) {
730 Abbrev->dropRef();
731 return false;
732 }
733 }
734
735 // Drop if we have already recorded this abbreviation with at least
736 // this number of instances.
jvoung (off chromium) 2014/02/06 23:19:37 When do collisions happen? Examples? How come it
Karl 2014/02/07 19:37:29 After thinking about this some more, the whole con
737 CandBlockAbbrev CandAbbrev(BlockID, Abbrev);
738 AbbrevCountMap::iterator Pos = AbbrevsMap.find(CandAbbrev);
739 if (Pos != AbbrevsMap.end() && Pos->second >= NumInstances) {
740 Abbrev->dropRef();
741 return false;
742 }
743
744 // If reached, we should add the given abbreviation to the set of
745 // candidate abbreviations.
746 if (NumInstances > GetMaxInstances()) {
747 // New range of candidates found. Throw out candidate
748 // abbreviations that no longer apply, due to the adjustment of
749 // the min/max ranges.
750 unsigned Bits = NaClBitsNeededForValue(NumInstances);
751 if (Bits > 31) {
752 MaxInstances = ~0U; // i.e. max unsigned value.
753 } else {
754 MaxInstances = 1U << Bits;
755 }
756
757 std::vector<CandBlockAbbrev> ToRemove;
758 for (const_iterator
759 Iter = AbbrevsMap.begin(), IterEnd = AbbrevsMap.end();
760 Iter != IterEnd; ++Iter) {
761 if (Iter->second < GetMinInstances()) {
762 ToRemove.push_back(Iter->first);
763 }
764 }
765
766 for (std::vector<CandBlockAbbrev>::const_iterator
767 Iter = ToRemove.begin(), IterEnd = ToRemove.end();
768 Iter != IterEnd; ++Iter) {
769 AbbrevsMap.erase(*Iter);
770 }
771 }
772
773 AbbrevsMap[CandAbbrev] = NumInstances;
774 return true;
775 }
776
777 // Look for new abbreviations in block BlockID, considering it was
778 // read with the given abbreviation Abbrev, and considering changing
779 // the abbreviation opererator for value Index. ValueDist is how
780 // values at Index are distributed. Any found abbreviations are added
781 // to the candidate abbreviations CandAbbrevs. Returns true only if we
782 // have added new candidate abbreviations to CandAbbrevs.
783 static bool AddNewAbbreviations(unsigned BlockID,
784 const UnrolledAbbreviation &Abbrev,
785 unsigned Index,
786 NaClBitcodeValueDist &ValueDist,
787 CandidateAbbrevs &CandAbbrevs) {
788 // TODO(kschimpf): Add code to try and find a better encoding for
789 // the values, based on the distribution.
790
791 // If this index is already a literal abbreviation, no improvements can
792 // be made.
793 const NaClBitCodeAbbrevOp Op = Abbrev.AbbrevOps[Index];
794 if (Op.isLiteral()) return false;
795
796 // Search based on sorted distribution, which sorts by number of
797 // instances. Start by trying to find possible constants to use.
798 const NaClBitcodeDist::Distribution *
799 Distribution = ValueDist.GetDistribution();
800 for (NaClBitcodeDist::Distribution::const_iterator
801 Iter = Distribution->begin(), IterEnd = Distribution->end();
802 Iter != IterEnd; ++Iter) {
803 NaClValueRangeType Range = GetNaClValueRange(Iter->second);
804 if (Range.first != Range.second) continue; // not a constant.
805
806 // Defines a constant. Try as new candidate range. In addition,
807 // don't try any more constant values, since this is the one with
808 // the greatest number of instances.
809 NaClBitcodeDistElement *Elmt = ValueDist.at(Range.first);
810 UnrolledAbbreviation CandAbbrev(Abbrev);
811 CandAbbrev.AbbrevOps[Index] = NaClBitCodeAbbrevOp(Range.first);
812 return CandAbbrevs.Add(BlockID, CandAbbrev, Elmt->GetNumInstances());
813 }
814 return false;
815 }
816
817 // Look for new abbreviations in block BlockID, considering it was
818 // read with the given abbreviation Abbrev. IndexDist is the
819 // corresponding distribution of value indices associated with the
820 // abbreviation. Any found abbreviations are added to the candidate
821 // abbreviations CandAbbrevs.
822 static void AddNewAbbreviations(unsigned BlockID,
823 const UnrolledAbbreviation &Abbrev,
824 NaClBitcodeDist &IndexDist,
825 CandidateAbbrevs &CandAbbrevs) {
826 // Search based on sorted distribution, which sorts based on heuristic
827 // of best index to fix first.
828 const NaClBitcodeDist::Distribution *
829 IndexDistribution = IndexDist.GetDistribution();
830 for (NaClBitcodeDist::Distribution::const_iterator
831 IndexIter = IndexDistribution->begin(),
832 IndexIterEnd = IndexDistribution->end();
833 IndexIter != IndexIterEnd; ++IndexIter) {
834 unsigned Index = static_cast<unsigned>(IndexIter->second);
835 if (AddNewAbbreviations(
836 BlockID, Abbrev, Index,
837 cast<NaClBitcodeValueIndexDistElement>(IndexDist.at(Index))
838 ->GetValueDist(),
839 CandAbbrevs)) {
840 return;
841 }
842 }
843 }
844
845 // Look for new abbreviations in block BlockID, considering it was
846 // read with the given abbreviation Abbrev, and the given record Code.
847 // SizeDist is the corresponding distribution of sizes associated with
848 // the abbreviation. Any found abbreviations are added to the
849 // candidate abbreviations CandAbbrevs.
850 static void AddNewAbbreviations(unsigned BlockID,
851 NaClBitCodeAbbrev *Abbrev,
852 unsigned Code,
853 NaClBitcodeDist &SizeDist,
854 CandidateAbbrevs &CandAbbrevs) {
855 const NaClBitcodeDist::Distribution *
856 SizeDistribution = SizeDist.GetDistribution();
857 for (NaClBitcodeDist::Distribution::const_iterator
858 SizeIter = SizeDistribution->begin(),
859 SizeIterEnd = SizeDistribution->end();
860 SizeIter != SizeIterEnd; ++SizeIter) {
861 unsigned Size = static_cast<unsigned>(SizeIter->second);
862 UnrolledAbbreviation UnrolledAbbrev(Abbrev, Size+1); // Add code!
863 if (!UnrolledAbbrev.CodeOp.isLiteral()) {
864 // Try making the code a literal.
865 UnrolledAbbreviation CandAbbrev(UnrolledAbbrev);
866 CandAbbrev.CodeOp = NaClBitCodeAbbrevOp(Code);
867 CandAbbrevs.Add(BlockID, CandAbbrev,
868 SizeDist.at(Size)->GetNumInstances());
869 }
870 // Now process value indices to find candidate abbreviations.
871 AddNewAbbreviations(
872 BlockID, UnrolledAbbrev,
873 cast<NaClBitcodeSizeDistElement>(SizeDist.at(Size))
874 ->GetValueIndexDist(),
875 CandAbbrevs);
876 }
877 }
878
879 // Look for new abbreviations in block BlockID. Abbrevs is the map of
880 // read (globally defined) abbreviations associated with the
881 // BlockID. AbbrevDist is the distribution map of abbreviations
882 // associated with BlockID. Any found abbreviations are added to the
883 // candidate abbreviations CandAbbrevs.
884 static void AddNewAbbreviations(unsigned BlockID,
885 BlockAbbrevs *Abbrevs,
886 NaClBitcodeDist &AbbrevDist,
887 CandidateAbbrevs &CandAbbrevs) {
888 const NaClBitcodeDist::Distribution *
889 AbbrevDistribution = AbbrevDist.GetDistribution();
890 for (NaClBitcodeDist::Distribution::const_iterator
891 AbbrevIter = AbbrevDistribution->begin(),
892 AbbrevIterEnd = AbbrevDistribution->end();
893 AbbrevIter != AbbrevIterEnd; ++AbbrevIter) {
894 NaClBitcodeDistValue AbbrevIndex = AbbrevIter->second;
895 NaClBitCodeAbbrev *Abbrev = Abbrevs->GetIndexedAbbrev(AbbrevIndex);
896 NaClBitcodeAbbrevDistElement *AbbrevElmt =
897 cast<NaClBitcodeAbbrevDistElement>(AbbrevDist.at(AbbrevIndex));
898 NaClBitcodeDist &CodeDist = AbbrevElmt->GetCodeDist();
899
900 const NaClBitcodeDist::Distribution *
901 CodeDistribution = CodeDist.GetDistribution();
902 for (NaClBitcodeDist::Distribution::const_iterator
903 CodeIter = CodeDistribution->begin(),
904 CodeIterEnd = CodeDistribution->end();
905 CodeIter != CodeIterEnd; ++CodeIter) {
906 unsigned Code = static_cast<unsigned>(CodeIter->second);
907 AddNewAbbreviations(
908 BlockID,
909 Abbrev,
910 Code,
911 cast<NaClCompressCodeDistElement>(CodeDist.at(CodeIter->second))
912 ->GetSizeDist(),
913 CandAbbrevs);
914 }
915 }
916 }
917
918 typedef std::pair<unsigned, CandBlockAbbrev> CountedAbbrevType;
919
920 // Look for new abbreviations in the given block distribution map
921 // BlockDist. BlockAbbrevsMap contains the set of read global
922 // abbreviations. Adds found candidate abbreviations to the set of
923 // known global abbreviations.
924 static void AddNewAbbreviations(NaClBitcodeBlockDist &BlockDist,
925 BlockAbbrevsMapType &BlockAbbrevsMap) {
926 CandidateAbbrevs CandAbbrevs(BlockAbbrevsMap);
927 // Start by collecting candidate abbreviations.
928 const NaClBitcodeDist::Distribution *
929 Distribution = BlockDist.GetDistribution();
930 for (NaClBitcodeDist::Distribution::const_iterator
931 Iter = Distribution->begin(), IterEnd = Distribution->end();
932 Iter != IterEnd; ++Iter) {
933 unsigned BlockID = static_cast<unsigned>(Iter->second);
934 AddNewAbbreviations(
935 BlockID,
936 BlockAbbrevsMap[BlockID],
937 cast<NaClCompressBlockDistElement>(BlockDist.at(BlockID))
938 ->GetAbbrevDist(),
939 CandAbbrevs);
940 }
941 // Install candidate abbreviations.
942 if (TraceGeneratedAbbreviations) {
943 CandAbbrevs.Print(errs(), "New abbreviations");
944 }
945 // Sort the candidate abbreviations by number of instances, so
946 // that if multiple abbreviations apply, the one with the largest
947 // number of instances will be chosen when generating compressed file.
948 std::vector<CountedAbbrevType> Candidates;
949 for (CandidateAbbrevs::const_iterator
950 Iter = CandAbbrevs.GetAbbrevsMap().begin(),
951 IterEnd = CandAbbrevs.GetAbbrevsMap().end();
952 Iter != IterEnd; ++Iter) {
953 Candidates.push_back(CountedAbbrevType(Iter->second,Iter->first));
954 }
955 std::sort(Candidates.begin(), Candidates.end());
956 for (std::vector<CountedAbbrevType>::const_reverse_iterator
957 Iter = Candidates.rbegin(), IterEnd = Candidates.rend();
958 Iter != IterEnd; ++Iter) {
959 BlockAbbrevs *Abbrevs = BlockAbbrevsMap[Iter->second.GetBlockID()];
960 Abbrevs->AddAbbreviation(Iter->second.GetAbbrev()->Copy());
961 }
962 }
963
511 // Read in bitcode, analyze data, and figure out set of abbreviations 964 // Read in bitcode, analyze data, and figure out set of abbreviations
512 // to use, from memory buffer MemBuf containing the input bitcode file. 965 // to use, from memory buffer MemBuf containing the input bitcode file.
513 static bool AnalyzeBitcode(OwningPtr<MemoryBuffer> &MemBuf, 966 static bool AnalyzeBitcode(OwningPtr<MemoryBuffer> &MemBuf,
514 BlockAbbrevsMapType &BlockAbbrevsMap) { 967 BlockAbbrevsMapType &BlockAbbrevsMap) {
515 // TODO(kschimpf): The current code only extracts abbreviations 968 // TODO(kschimpf): The current code only extracts abbreviations
516 // defined in the bitcode file. This code needs to be updated to 969 // defined in the bitcode file. This code needs to be updated to
517 // collect data distributions and figure out better (global) 970 // collect data distributions and figure out better (global)
518 // abbreviations to use. 971 // abbreviations to use.
519 972
520 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart(); 973 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
(...skipping 14 matching lines...) Expand all
535 if (Parser.Parse()) return true; 988 if (Parser.Parse()) return true;
536 } 989 }
537 990
538 if (ShowValueDistributions) { 991 if (ShowValueDistributions) {
539 // To make shell redirection of this trace easier, print it to 992 // To make shell redirection of this trace easier, print it to
540 // stdout unless stdout is being used to contain the compressed 993 // stdout unless stdout is being used to contain the compressed
541 // bitcode file. In the latter case, use stderr. 994 // bitcode file. In the latter case, use stderr.
542 Parser.BlockDist.Print(OutputFilename == "-" ? errs() : outs()); 995 Parser.BlockDist.Print(OutputFilename == "-" ? errs() : outs());
543 } 996 }
544 997
998 AddNewAbbreviations(Parser.BlockDist, BlockAbbrevsMap);
545 return false; 999 return false;
546 } 1000 }
547 1001
548 /// Parses the input bitcode file and generates the corresponding 1002 /// Parses the input bitcode file and generates the corresponding
549 /// compressed bitcode file, by replacing abbreviations in the input 1003 /// compressed bitcode file, by replacing abbreviations in the input
550 /// file with the corresponding abbreviations defined in 1004 /// file with the corresponding abbreviations defined in
551 /// BlockAbbrevsMap. 1005 /// BlockAbbrevsMap.
552 class NaClBitcodeCopyParser : public NaClBitcodeParser { 1006 class NaClBitcodeCopyParser : public NaClBitcodeParser {
553 public: 1007 public:
554 // Top-level constructor to build the appropriate block parser 1008 // Top-level constructor to build the appropriate block parser
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
616 NaClBlockCopyParser *EnclosingParser) 1070 NaClBlockCopyParser *EnclosingParser)
617 : NaClBitcodeParser(BlockID, EnclosingParser), 1071 : NaClBitcodeParser(BlockID, EnclosingParser),
618 Context(EnclosingParser->Context) 1072 Context(EnclosingParser->Context)
619 {} 1073 {}
620 1074
621 virtual bool Error(const std::string &Message) { 1075 virtual bool Error(const std::string &Message) {
622 // Use local error routine so that all errors are treated uniformly. 1076 // Use local error routine so that all errors are treated uniformly.
623 return ::Error(Message); 1077 return ::Error(Message);
624 } 1078 }
625 1079
1080 /// Returns the set of (global) block abbreviations defined for the
1081 /// given block ID.
1082 BlockAbbrevs *GetGlobalAbbrevs(unsigned BlockID) {
1083 BlockAbbrevs *Abbrevs = Context->BlockAbbrevsMap[BlockID];
1084 if (Abbrevs == 0) {
1085 Abbrevs = new BlockAbbrevs(BlockID);
1086 Context->BlockAbbrevsMap[BlockID] = Abbrevs;
1087 }
1088 return Abbrevs;
1089 }
1090
626 virtual bool ParseBlock(unsigned BlockID) { 1091 virtual bool ParseBlock(unsigned BlockID) {
627 NaClBlockCopyParser Parser(BlockID, this); 1092 NaClBlockCopyParser Parser(BlockID, this);
628 return Parser.ParseThisBlock(); 1093 return Parser.ParseThisBlock();
629 } 1094 }
630 1095
631 virtual void EnterBlock(unsigned NumWords) { 1096 virtual void EnterBlock(unsigned NumWords) {
632 unsigned BlockID = GetBlockID(); 1097 unsigned BlockID = GetBlockID();
633 BlockAbbreviations = Context->BlockAbbrevsMap[BlockID]; 1098 BlockAbbreviations = GetGlobalAbbrevs(BlockID);
634 1099
635 // Enter the subblock. 1100 // Enter the subblock.
636 NaClBitcodeSelectorAbbrev 1101 NaClBitcodeSelectorAbbrev
637 Selector(BlockAbbreviations->GetNumberAbbreviations()-1); 1102 Selector(BlockAbbreviations->GetNumberAbbreviations()-1);
638 Context->Writer.EnterSubblock(BlockID, Selector); 1103 Context->Writer.EnterSubblock(BlockID, Selector);
1104
1105 // Note: We must dump module abbreviations as local
1106 // abbreviations, because they are in a yet to be
1107 // dumped BlockInfoBlock.
1108 if (BlockID == naclbitc::MODULE_BLOCK_ID) {
1109 BlockAbbrevs* Abbrevs = GetGlobalAbbrevs(naclbitc::MODULE_BLOCK_ID);
1110 if (Abbrevs == 0) return;
jvoung (off chromium) 2014/02/06 23:19:37 when can Abbrevs == 0, if Abbrevs is returned by G
Karl 2014/02/07 19:37:29 Removed.
1111 for (unsigned i = 0; i < Abbrevs->GetNumberAbbreviations(); ++i) {
1112 Context->Writer.EmitAbbrev(Abbrevs->GetIndexedAbbrev(i)->Copy());
1113 }
1114 }
639 } 1115 }
640 1116
641 virtual void ExitBlock() { 1117 virtual void ExitBlock() {
642 Context->Writer.ExitBlock(); 1118 Context->Writer.ExitBlock();
643 } 1119 }
644 1120
645 virtual void ExitBlockInfo() { 1121 virtual void ExitBlockInfo() {
646 assert(!Context->FoundFirstBlockInfo && 1122 assert(!Context->FoundFirstBlockInfo &&
647 "Input bitcode has more that one BlockInfoBlock"); 1123 "Input bitcode has more that one BlockInfoBlock");
648 Context->FoundFirstBlockInfo = true; 1124 Context->FoundFirstBlockInfo = true;
649 1125
650 // Generate global abbreviations within a blockinfo block. 1126 // Generate global abbreviations within a blockinfo block.
651 Context->Writer.EnterBlockInfoBlock(); 1127 Context->Writer.EnterBlockInfoBlock();
652 for (BlockAbbrevsMapType::const_iterator 1128 for (BlockAbbrevsMapType::const_iterator
653 Iter = Context->BlockAbbrevsMap.begin(), 1129 Iter = Context->BlockAbbrevsMap.begin(),
654 IterEnd = Context->BlockAbbrevsMap.end(); 1130 IterEnd = Context->BlockAbbrevsMap.end();
655 Iter != IterEnd; ++Iter) { 1131 Iter != IterEnd; ++Iter) {
656 unsigned BlockID = Iter->first; 1132 unsigned BlockID = Iter->first;
1133 // Don't emit module abbreviations, since they have been
1134 // emitted as local abbreviations.
1135 if (BlockID == naclbitc::MODULE_BLOCK_ID) continue;
1136
657 BlockAbbrevs *Abbrevs = Iter->second; 1137 BlockAbbrevs *Abbrevs = Iter->second;
658 if (Abbrevs == 0) continue; 1138 if (Abbrevs == 0) continue;
659 for (unsigned i = Abbrevs->GetFirstApplicationAbbreviation(); 1139 for (unsigned i = Abbrevs->GetFirstApplicationAbbreviation();
660 i < Abbrevs->GetNumberAbbreviations(); ++i) { 1140 i < Abbrevs->GetNumberAbbreviations(); ++i) {
661 NaClBitCodeAbbrev *Abbrev = Abbrevs->GetIndexedAbbrev(i); 1141 NaClBitCodeAbbrev *Abbrev = Abbrevs->GetIndexedAbbrev(i);
662 Context->Writer.EmitBlockInfoAbbrev(BlockID, Abbrev); 1142 Context->Writer.EmitBlockInfoAbbrev(BlockID, Abbrev);
663 } 1143 }
664 } 1144 }
665 Context->Writer.ExitBlock(); 1145 Context->Writer.ExitBlock();
666 } 1146 }
(...skipping 281 matching lines...) Expand 10 before | Expand all | Expand 10 after
948 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 1428 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
949 cl::ParseCommandLineOptions(argc, argv, "pnacl-bccompress file analyzer\n"); 1429 cl::ParseCommandLineOptions(argc, argv, "pnacl-bccompress file analyzer\n");
950 1430
951 OwningPtr<MemoryBuffer> MemBuf; 1431 OwningPtr<MemoryBuffer> MemBuf;
952 if (ReadAndBuffer(MemBuf)) return 1; 1432 if (ReadAndBuffer(MemBuf)) return 1;
953 BlockAbbrevsMapType BlockAbbrevsMap; 1433 BlockAbbrevsMapType BlockAbbrevsMap;
954 if (AnalyzeBitcode(MemBuf, BlockAbbrevsMap)) return 1; 1434 if (AnalyzeBitcode(MemBuf, BlockAbbrevsMap)) return 1;
955 if (CopyBitcode(MemBuf, BlockAbbrevsMap)) return 1; 1435 if (CopyBitcode(MemBuf, BlockAbbrevsMap)) return 1;
956 return 0; 1436 return 0;
957 } 1437 }
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