OpenASIP  2.0
CompiledSimController.cc
Go to the documentation of this file.
1 /*
2  Copyright (c) 2002-2010 Tampere University.
3 
4  This file is part of TTA-Based Codesign Environment (TCE).
5 
6  Permission is hereby granted, free of charge, to any person obtaining a
7  copy of this software and associated documentation files (the "Software"),
8  to deal in the Software without restriction, including without limitation
9  the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  and/or sell copies of the Software, and to permit persons to whom the
11  Software is furnished to do so, subject to the following conditions:
12 
13  The above copyright notice and this permission notice shall be included in
14  all copies or substantial portions of the Software.
15 
16  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  DEALINGS IN THE SOFTWARE.
23  */
24 /**
25  * @file CompiledSimController.cc
26  *
27  * Definition of CompiledSimController class.
28  *
29  * @author Viljami Korhonen 2007 (viljami.korhonen-no.spam-tut.fi)
30  * @author Pekka Jääskeläinen 2010
31  * @note rating: red
32  */
33 
34 #include <cstdlib>
35 
36 #include "SimulatorFrontend.hh"
37 #include "CompiledSimController.hh"
39 #include "CompiledSimCompiler.hh"
40 #include "FileSystem.hh"
41 #include "MemorySystem.hh"
42 #include "SimulatorToolbox.hh"
43 #include "CompiledSimulation.hh"
44 #include "POMValidator.hh"
45 #include "POMValidatorResults.hh"
46 #include "Instruction.hh"
47 #include "MathTools.hh"
48 #include "Program.hh"
50 #include "Conversion.hh"
51 #include "Machine.hh"
52 
53 using std::endl;
54 using namespace TTAMachine;
55 
56 //#define DEBUG_COMPILED_SIMULATION
57 
58 /**
59  * The constructor
60  *
61  * @param frontend Simulator frontend
62  * @param machine The machine model
63  * @param program The program to be simulated
64  * @param leaveDirty Set to true in case the engine should not clean up the
65  * source files to the engine (in /tmp) after finishing,
66  * e.g., for debugging purposes.
67  */
70  const TTAProgram::Program& program, bool leaveDirty) :
72  pluginTools_(true, false), compiledSimulationPath_(""),
73  leaveDirty_(leaveDirty) {
74 
75 #ifdef DEBUG_COMPILED_SIMULATION
76  leaveDirty_ = true;
77 #endif
78 
79  // Make the symbols unique in case we use more than one
80  // simulator engines in the same process.
81  static int instanceCount = 0;
82  instanceId_ = instanceCount;
83 
84  // Note, this is not thread safe. Thus, the engines should be
85  // initialized sequentially.
86  ++instanceCount;
87 
88  reset();
89 }
90 
91 /**
92  * The destructor
93  */
96 }
97 
98 /**
99  * Advances simulation by given amount of cycles
100  *
101  * @Note The accuracy of this function is one basic block!
102  */
103 void
106  stopReasons_.clear();
108  stopRequested_ = false;
109 
110  try {
111  simulation_->step(count);
112  } catch (const Exception& e) {
114  return;
115  } catch(...) {
117  return;
118  }
119 
121 
122  if (simulation_->isFinished()) {
124  } else {
126  }
127 
130 }
131 
132 /**
133  * Advances simulation by a given amout of steps and skip procedure calls.,
134  *
135  * @Note The accuracy of this function is one basic block!
136  */
137 void
140  stopReasons_.clear();
142  stopRequested_ = false;
143 
144  try {
145  simulation_->next(count);
146  } catch (const Exception& e) {
148  return;
149  } catch(...) {
151  return;
152  }
153 
155 
156  if (simulation_->isFinished()) {
158  } else {
160  }
161 
164 }
165 
166 /**
167  * Advances the simulation until the program ends
168  *
169  * @exception SimulationExecutionError If a runtime error occurs in
170  * the simulated program.
171  */
172 void
174  stopRequested_ = false;
175  stopReasons_.clear();
177 
178  // Run the program
179  try {
180  simulation_->run();
181  } catch (const Exception& e) {
183  return;
184  } catch(...) {
186  return;
187  }
188 
189  if (simulation_->isFinished()) {
191  } else {
193  }
194 
197 }
198 
199 /**
200  * Advances the simulation until a given address is reached.
201  *
202  * @Note The accuracy of this function is one basic block!
203  *
204  * @param address the address after the simulation execution should end
205  * @exception SimulationExecutionError If a runtime error occurs in
206  * the simulated program.
207  */
208 void
210  stopRequested_ = false;
211  stopReasons_.clear();
213  address = basicBlockStart(address); // find nearest bb start
214 
215  try {
216  simulation_->runUntil(address);
217  } catch (const Exception& e) {
219  return;
220  } catch(...) {
222  return;
223  }
224 
226 
227  if (simulation_->isFinished()) {
229  } else {
231  }
232 
235 }
236 
237 /**
238  * Resets the simulation so it can be started from the beginning.
239  *
240  * Resets everything to initial values (program counter, clock cycles etc.)
241  */
242 void
244 
246  stopRequested_ = false;
247  clockCount_ = 0;
248 
250 
252  if (compiledSimulationPath_ == "") {
254  << "Cannot create temporary path "
255  << "for the generated simulation code!" << endl;
256  return;
257  }
258 
259  // Generate all simulation code at once
260  CompiledSimCodeGenerator generator(
261  sourceMachine_, program_, *this,
265  false, !frontend_.staticCompilation(),
267 
269 #ifdef DEBUG_COMPILED_SIMULATION
270  std::cerr << "Generated compiled simulation sources to: '"
271  << compiledSimulationPath_ << "'" << std::endl;
272 #endif
273  basicBlocks_ = generator.basicBlocks();
275 
276  CompiledSimCompiler compiler;
277 
278  // Compile everything when using static compiled simulation
280  if (compiler.compileDirectory(compiledSimulationPath_, "", false)
281  != 0) {
282  Application::logStream() << "Compilation aborted." << endl;
283  return;
284  }
285  } else { // Compile main engine file
287  + FileSystem::DIRECTORY_SEPARATOR + "CompiledSimulationEngine.cc");
288 
289  // Precompile the simulation header
291  + FileSystem::DIRECTORY_SEPARATOR + "CompiledSimulationEngine.hh",
292  "-xc++-header", ".gch");
293  }
294 
295  SimulationGetterFunction* simulationGetter = NULL;
297 
298  // register individual simulation functions
299  std::vector<std::string> sos;
300  FileSystem::globPath(compiledSimulationPath_ + "/simulate_*.so", sos);
301  for (std::size_t i = 0; i < sos.size(); ++i) {
302  const std::string& so = FileSystem::fileOfPath(sos.at(i));
304  }
305 
306  // register simulation getter function symbol
307  pluginTools_.registerModule("CompiledSimulationEngine.so");
309  "getSimulation_" + Conversion::toString(instanceId_), simulationGetter);
310  simulation_.reset(
311  simulationGetter(sourceMachine_, program_.entryAddress().location(),
315 
317 }
318 
319 /**
320  * Returns the program counter value.
321  *
322  * @return Program counter value.
323  */
326  return simulation_->programCounter();
327 }
328 
329 /**
330  * Returns the address of the last executed instruction.
331  *
332  * @return The address of the last executed instruction
333  */
336  return simulation_->lastExecutedInstruction();
337 }
338 
339 /**
340  * Returns the count of clock cycles simulated.
341  *
342  * @return Count of simulated clock cycles.
343  */
346  if (simulation_) {
347  return simulation_->cycleCount();
348  } else {
349  return 0;
350  }
351 }
352 
353 /**
354  * Returns a pointer to the current CompiledSimulation object
355  *
356  * @return A pointer to the current CompiledSimulation object
357  */
358 boost::shared_ptr<CompiledSimulation>
360  return simulation_;
361 }
362 
363 /**
364  * Will delete all generated code files if leaveDirty_ is not set
365  */
366 void
368  if (leaveDirty_) {
369  return;
370  }
371 
373  && compiledSimulationPath_ != "") {
375  }
376 }
377 
378 /**
379  * Returns the start of the basic block containing address
380  *
381  * @param address
382  * @return instruction address of the basic block start
383  */
386  return basicBlocks_.lower_bound(address)->second;
387 }
388 
389 /**
390  * Returns the program model
391  * @return the program model
392  */
393 const TTAProgram::Program&
395  return program_;
396 }
397 
398 /**
399  * Returns a string containing the value(s) of the register file
400  *
401  * @param rfName name of the register file to search for
402  * @param registerIndex index of the register. if -1, all registers are listed
403  * @return A string containing the value(s) of the register file
404  * @exception InstanceNotFound If the register cannot be found.
405  */
406 std::string
408  const std::string& rfName, int registerIndex) {
409  std::string stringValue("");
410 
411  if (registerIndex >= 0) {
412  stringValue += compiledSimulation()->
413  registerFileValue(rfName.c_str(), registerIndex).hexValue();
414  } else {
415  Machine::RegisterFileNavigator navigator =
417  RegisterFile& rf = *navigator.item(rfName);
418 
419  bool firstReg = true;
420  for (int i = 0; i < rf.numberOfRegisters(); ++i) {
421  if (!firstReg)
422  stringValue += "\n";
423  const std::string registerName =
424  rfName + "." + Conversion::toString(i);
425 
426  SimValue value = compiledSimulation()->
427  registerFileValue(rfName.c_str(), i);
428  stringValue += registerName + " " + value.hexValue();
429 
430  firstReg = false;
431  }
432  }
433 
434  return stringValue;
435 }
436 
437 /**
438  * Returns the current value of a IU register
439  *
440  * @param iuName name of the immediate unit
441  * @param index index of the register
442  * @return Current value of a IU register
443  */
444 SimValue
446  const std::string& iuName,
447  int index) {
448  return compiledSimulation()->immediateUnitRegisterValue(iuName.c_str(),
449  index);
450 }
451 
452 /**
453  * Returns a FU port's value
454  *
455  * @param fuName name of the function unit
456  * @param portIndex Index of the port
457  * @return A FU port's value
458  */
459 SimValue
461  const std::string& fuName,
462  const std::string& portName) {
463  return compiledSimulation()->FUPortValue(fuName.c_str(), portName.c_str());
464 }
465 
466 /**
467  * Sends a stop request to the simulation controller and compiled simulation
468  *
469  * @param reason The stop reason
470  */
471 void
474  compiledSimulation()->requestToStop();
475 }
CompiledSimCompiler::compileDirectory
int compileDirectory(const std::string &dirName, const std::string &flags="", bool verbose=false) const
Definition: CompiledSimCompiler.cc:125
TTASimulationController::memorySystem
virtual MemorySystem & memorySystem(int coreId=-1)
Definition: TTASimulationController.cc:171
CompiledSimController::compiledSimulationPath_
std::string compiledSimulationPath_
Path to the generated simulation files.
Definition: CompiledSimController.hh:120
UIntWord
Word UIntWord
Definition: BaseType.hh:144
TTAProgram::Program
Definition: Program.hh:63
InstructionAddress
UInt32 InstructionAddress
Definition: BaseType.hh:175
CompiledSimCodeGenerator::basicBlocks
virtual AddressMap basicBlocks() const
Definition: CompiledSimCodeGenerator.cc:317
FileSystem.hh
CompiledSimController::next
virtual void next(int count=1)
Definition: CompiledSimController.cc:138
FileSystem::removeFileOrDirectory
static bool removeFileOrDirectory(const std::string &path)
Definition: FileSystem.cc:493
TTASimulationController::STA_STOPPED
@ STA_STOPPED
Simulation stopped for some reason.
Definition: TTASimulationController.hh:76
TTASimulationController::stopReasons_
StopReasonContainer stopReasons_
The set of reasons the simulation was stopped.
Definition: TTASimulationController.hh:144
SimulatorFrontend::procedureTransferTracing
bool procedureTransferTracing() const
Definition: SimulatorFrontend.cc:1827
machine
TTAMachine::Machine * machine
the architecture definition of the estimated processor
Definition: EstimatorCmdLineUI.cc:59
TTAProgram::Program::entryAddress
Address entryAddress() const
Definition: Program.cc:330
SimulationEventHandler::SE_SIMULATION_STOPPED
@ SE_SIMULATION_STOPPED
Generated after simulation has stopped, temporarily or permantently, and control is being returned to...
Definition: SimulationEventHandler.hh:54
CompiledSimController::run
virtual void run()
Definition: CompiledSimController.cc:173
CompiledSimCodeGenerator.hh
SimulatorFrontend::fuResourceConflictDetection
bool fuResourceConflictDetection() const
Definition: SimulatorFrontend.cc:2032
CompiledSimController::FUPortValue
virtual SimValue FUPortValue(const std::string &fuName, const std::string &portName)
Definition: CompiledSimController.cc:460
CompiledSimController::clockCount
virtual ClockCycleCount clockCount() const
Definition: CompiledSimController.cc:345
CompiledSimController::SimulationGetterFunction
CompiledSimulation *() SimulationGetterFunction(const TTAMachine::Machine &machine, InstructionAddress entryAddress, InstructionAddress lastInstruction, SimulatorFrontend &frontend, CompiledSimController &controller, MemorySystem &memorySystem, bool dynamicCompilation, ProcedureBBRelations &procedureBBRelations)
Function type for the getSimulation() function.
Definition: CompiledSimController.hh:81
FileSystem::globPath
static void globPath(const std::string &pattern, std::vector< std::string > &filenames)
Definition: FileSystem.cc:197
Application::logStream
static std::ostream & logStream()
Definition: Application.cc:155
TTASimulationController::prepareToStop
virtual void prepareToStop(StopReason reason)
Definition: TTASimulationController.cc:90
MemorySystem.hh
CompiledSimController::prepareToStop
virtual void prepareToStop(StopReason reason)
Definition: CompiledSimController.cc:472
CompiledSimController::lastExecutedInstruction
virtual InstructionAddress lastExecutedInstruction() const
Definition: CompiledSimController.cc:335
FileSystem::fileOfPath
static std::string fileOfPath(const std::string pathName)
Definition: FileSystem.cc:101
Conversion::toString
static std::string toString(const T &source)
SimulatorFrontend::staticCompilation
bool staticCompilation() const
Definition: SimulatorFrontend.cc:1857
CompiledSimCompiler
Definition: CompiledSimCompiler.hh:41
SimValue
Definition: SimValue.hh:96
TTAMachine::BaseRegisterFile::numberOfRegisters
virtual int numberOfRegisters() const
POMValidatorResults.hh
TTASimulationController::STA_RUNNING
@ STA_RUNNING
A run command (run, stepi, until...) given.
Definition: TTASimulationController.hh:75
assert
#define assert(condition)
Definition: Application.hh:86
CompiledSimController::immediateUnitRegisterValue
virtual SimValue immediateUnitRegisterValue(const std::string &iuName, int index=-1)
Definition: CompiledSimController.cc:445
TTASimulationController::state_
SimulationStatus state_
The current state of the simulation.
Definition: TTASimulationController.hh:147
SimulationEventHandler.hh
TTASimulationController::frontend_
SimulatorFrontend & frontend_
Reference to the simulator frontend.
Definition: TTASimulationController.hh:135
SimulatorToolbox.hh
TTASimulationController
Definition: TTASimulationController.hh:69
CompiledSimController::procedureBBRelations_
ProcedureBBRelations procedureBBRelations_
A struct for tracking basic blocks and their relation to their procedures.
Definition: CompiledSimController.hh:128
CompiledSimController::deleteGeneratedFiles
virtual void deleteGeneratedFiles()
Definition: CompiledSimController.cc:367
CompiledSimController::pluginTools_
PluginTools pluginTools_
Used for loading the compiled simulation plugin.
Definition: CompiledSimController.hh:114
PluginTools::importSymbol
void importSymbol(const std::string &symbolName, T *&target, const std::string &module)
Instruction.hh
TTASimulationController::STA_INITIALIZED
@ STA_INITIALIZED
Simulation initialized and ready to run.
Definition: TTASimulationController.hh:74
TTASimulationController::STA_FINISHED
@ STA_FINISHED
Simulation ended after executing the last instruction.
Definition: TTASimulationController.hh:77
CompiledSimController::registerFileValue
virtual std::string registerFileValue(const std::string &rfName, int registerIndex=-1)
Definition: CompiledSimController.cc:407
Conversion.hh
CompiledSimController::programCounter
virtual InstructionAddress programCounter() const
Definition: CompiledSimController.cc:325
CompiledSimCodeGenerator
Definition: CompiledSimCodeGenerator.hh:99
TTASimulationController::sourceMachine_
const TTAMachine::Machine & sourceMachine_
The simulated Machine Object Model.
Definition: TTASimulationController.hh:137
PluginTools::registerModule
void registerModule(const std::string &module)
Definition: PluginTools.cc:138
CompiledSimController::~CompiledSimController
virtual ~CompiledSimController()
Definition: CompiledSimController.cc:94
TTASimulationController::stopRequested_
bool stopRequested_
Flag indicating that simulation should stop.
Definition: TTASimulationController.hh:142
StopReason
StopReason
The reasons to stop simulation.
Definition: SimulatorConstants.hh:60
TTAProgram::Address::location
InstructionAddress location() const
SRE_RUNTIME_ERROR
@ SRE_RUNTIME_ERROR
A fatal runtime error occured in the simulated program.
Definition: SimulatorConstants.hh:68
Machine.hh
CompiledSimController::leaveDirty_
bool leaveDirty_
True, if the simulation should leave all the generated code files.
Definition: CompiledSimController.hh:123
Exception
Definition: Exception.hh:54
TTASimulationController::STA_INITIALIZING
@ STA_INITIALIZING
Simulation is being initialized.
Definition: TTASimulationController.hh:73
SRE_AFTER_UNTIL
@ SRE_AFTER_UNTIL
Stopped after running to the wanted.
Definition: SimulatorConstants.hh:62
SimulatorFrontend.hh
CompiledSimulation.hh
CompiledSimController::step
virtual void step(double count=1)
Definition: CompiledSimController.cc:104
CompiledSimCompiler.hh
TTASimulationController::clockCount_
ClockCycleCount clockCount_
How many clock cycles have been simulated.
Definition: TTASimulationController.hh:149
SimValue::hexValue
TCEString hexValue(bool noHexIdentifier=false) const
Definition: SimValue.cc:1150
FileSystem::DIRECTORY_SEPARATOR
static const std::string DIRECTORY_SEPARATOR
Definition: FileSystem.hh:189
CompiledSimController::runUntil
virtual void runUntil(UIntWord address)
Definition: CompiledSimController.cc:209
CompiledSimCompiler::compileFile
int compileFile(const std::string &path, const std::string &flags="", const std::string &outputExtension=".o", bool verbose=false) const
Definition: CompiledSimCompiler.cc:168
CompiledSimController::instanceId_
int instanceId_
The unique identifier for this simulation engine. Used for enabling multiple compiled engines in the ...
Definition: CompiledSimController.hh:133
CompiledSimController::basicBlockStart
InstructionAddress basicBlockStart(InstructionAddress address) const
Definition: CompiledSimController.cc:385
CompiledSimController::program
const TTAProgram::Program & program() const
Definition: CompiledSimController.cc:394
TTAMachine::Machine::registerFileNavigator
virtual RegisterFileNavigator registerFileNavigator() const
Definition: Machine.cc:450
CompiledSimController::compiledSimulation
virtual boost::shared_ptr< CompiledSimulation > compiledSimulation()
Definition: CompiledSimController.cc:359
Program.hh
SimulatorFrontend::eventHandler
SimulationEventHandler & eventHandler()
Definition: SimulatorFrontend.cc:2260
CATCH_ANY
#define CATCH_ANY(XXX__)
Definition: Application.hh:100
CompiledSimController::simulation_
boost::shared_ptr< CompiledSimulation > simulation_
Pointer to the loaded simulation.
Definition: CompiledSimController.hh:117
false
find Finds info of the inner loops in the false
Definition: InnerLoopFinder.cc:81
PluginTools::addSearchPath
void addSearchPath(const std::string &searchPath)
Definition: PluginTools.cc:95
FileSystem::fileExists
static bool fileExists(const std::string fileName)
SRE_AFTER_STEPPING
@ SRE_AFTER_STEPPING
Stopped after stepping the given count.
Definition: SimulatorConstants.hh:61
CompiledSimCompiler::compileToSO
int compileToSO(const std::string &path, const std::string &flags="", bool verbose=false) const
Definition: CompiledSimCompiler.cc:210
CompiledSimCodeGenerator::generateToDirectory
virtual void generateToDirectory(const std::string &dirName)
Definition: CompiledSimCodeGenerator.cc:231
ClockCycleCount
CycleCount ClockCycleCount
Alias for ClockCycleCount.
Definition: SimulatorConstants.hh:57
SimulatorFrontend::executionTracing
bool executionTracing() const
Definition: SimulatorFrontend.cc:1798
CompiledSimController::reset
virtual void reset()
Definition: CompiledSimController.cc:243
TTAMachine::Machine::Navigator::item
ComponentType * item(int index) const
program
find Finds info of the inner loops in the program
Definition: InnerLoopFinder.cc:80
CompiledSimCodeGenerator::procedureBBRelations
virtual ProcedureBBRelations procedureBBRelations() const
Definition: CompiledSimCodeGenerator.cc:330
TTAMachine::RegisterFile
Definition: RegisterFile.hh:47
TTAProgram::Program::lastInstruction
Instruction & lastInstruction() const
Definition: Program.cc:463
MathTools.hh
Informer::handleEvent
void handleEvent(int event)
TTAMachine
Definition: Assembler.hh:48
CompiledSimController.hh
TTASimulationController::program_
const TTAProgram::Program & program_
Program object model of the simulated program.
Definition: TTASimulationController.hh:139
CompiledSimController::basicBlocks_
CompiledSimCodeGenerator::AddressMap basicBlocks_
A map containing the basic blocks' start..end pairs.
Definition: CompiledSimController.hh:126
CompiledSimController::CompiledSimController
CompiledSimController(SimulatorFrontend &frontend, const TTAMachine::Machine &machine, const TTAProgram::Program &program, bool leaveDirty=false)
Definition: CompiledSimController.cc:68
TTAMachine::Machine::Navigator
Definition: Machine.hh:186
SimulatorFrontend
Definition: SimulatorFrontend.hh:89
FileSystem::createTempDirectory
static std::string createTempDirectory(const std::string &path="/tmp", const std::string &tempDirPrefix="tmp_tce_")
Definition: FileSystem.cc:441
POMValidator.hh
TTAProgram::Instruction::address
Address address() const
Definition: Instruction.cc:327
TTAMachine::Machine
Definition: Machine.hh:73