/* ILEngineer - Crummy .NET Decompiler
 * Copyright (C) 2001-2002  Jay Freeman (saurik)
*/

/*
 *        Redistribution and use in source and binary
 * forms, with or without modification, are permitted
 * provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the
 *    above copyright notice, this list of conditions
 *    and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions
 *    and the following disclaimer in the documentation
 *    and/or other materials provided with the
 *    distribution.
 * 3. The name of the author may not be used to endorse
 *    or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "stdafx.h"
#include "ilengineer/Block.h"

#include "ilengineer/Blocks/Lock.h"
#include "ilengineer/Blocks/Method.h"
#include "ilengineer/Blocks/Try.h"

#include "ilengineer/Ops/MSIL/Call.h"
#include "ilengineer/Ops/MSIL/LoadLocal.h"
#include "ilengineer/Ops/MSIL/StoreLocal.h"

void ILEngineer::Block::OptimizeLock() {
	for (StatementVector::iterator stI(m_Statements.begin()); stI != m_Statements.end(); stI++)
		if ((*stI)->isBlock())
			dynamic_cast<Block *>(*stI)->OptimizeLock();

	for (int i(0); i < ((int) m_Statements.size()) - 3; i++) {
		Statement *st1 = m_Statements[i+0];
		Blocks::Try *triumph = dynamic_cast<Blocks::Try *>(m_Statements[i+1]);
		Blocks::Finally *final = dynamic_cast<Blocks::Finally *>(m_Statements[i+2]);

		if (!st1->isBlock() && triumph != NULL && final != NULL && (i + 3 == (int) m_Statements.size() || (
			typeid(*m_Statements[i+3]) != typeid(Blocks::Catch) && typeid(*m_Statements[i+3]) != typeid(Blocks::Finally))))
		{
			Ops::MSIL::Call *menter = dynamic_cast<Ops::MSIL::Call *>(st1->getOperations()[0]);
			StatementVector &finals = final->getStatements();

			if (menter != NULL) {
				Ops::MSIL::StoreLocal *store = dynamic_cast<Ops::MSIL::StoreLocal *>(menter->getOperations()[0]);
				if (store != NULL) {
					Metallurgy::Member *member = menter->getMember();

					if (member->is(L"System.Threading.Monitor", L"Enter") &&
						finals.size() == 1 && !finals[0]->isBlock())
					{
						Ops::MSIL::Call *mexit = dynamic_cast<Ops::MSIL::Call *>(finals[0]->getOperations()[0]);

						if (mexit != NULL) {
							Metallurgy::Member *member = mexit->getMember();

							if (member->is(L"System.Threading.Monitor", L"Exit")) {
								Ops::MSIL::LoadLocal *load = dynamic_cast<Ops::MSIL::LoadLocal *>(mexit->getOperations()[0]);

								if (load != NULL && load->getIndx() == store->getIndx()) {
									Blocks::Lock *lock = new Blocks::Lock(m_Method, triumph, store->getValue(), st1->getOffset());
									store->toTrash();

									m_Statements.erase(m_Statements.begin() + i); delete st1;
									m_Statements.erase(m_Statements.begin() + i); delete triumph;

									m_Statements[i] = lock;
									delete final;
								}
							}
						}
					}
				}
			}
		}
	}

	/*for (int i(0); i < ((int) m_Statements.size()) - 3; i++) {
		Statement *st1(m_Statements[i+0]), *st2(m_Statements[i+1]), *st3(m_Statements[i+2]);
		if (!st1->isBlock() && !st2->isBlock() && typeid(*st3) == typeid(Blocks::Try)) {
			Ops::MSIL::StoreLocal *store = dynamic_cast<Ops::MSIL::StoreLocal *>(st1->getOperations()[0]);
			Ops::MSIL::Call *menter = dynamic_cast<Ops::MSIL::Call *>(st2->getOperations()[0]);
			Blocks::Try *triumph = dynamic_cast<Blocks::Try *>(st3);

			if (store != NULL && menter != NULL &&
				triumph->getCatches().size() == 0 &&
				triumph->getFinallies().size() == 1)
			{
				Blocks::Finally *final = dynamic_cast<Blocks::Finally *>(triumph->getFinallies()[0]);
				StatementVector &finals = final->getStatements();
				Metallurgy::Member *member = m_Method->getImport()->getMember(menter->getMember());

				if (member->is(L"System.Threading.Monitor", L"Enter") &&
					finals.size() == 1 && !finals[0]->isBlock())
				{
					Ops::MSIL::Duplicate *dup1 = dynamic_cast<Ops::MSIL::Duplicate *>(store->getValue());
					Ops::MSIL::Duplicate *dup2 = dynamic_cast<Ops::MSIL::Duplicate *>(menter->getOperations()[0]);
					Ops::MSIL::Call *mexit = dynamic_cast<Ops::MSIL::Call *>(finals[0]->getOperations()[0]);

					if (mexit != NULL && dup1 != NULL && dup2 != NULL && dup1->getValue() == dup2->getValue()) {
						Metallurgy::Member *member = m_Method->getImport()->getMember(mexit->getMember());

						if (member->is(L"System.Threading.Monitor", L"Exit")) {
							Ops::MSIL::LoadLocal *load = dynamic_cast<Ops::MSIL::LoadLocal *>(mexit->getOperations()[0]);

							if (load != NULL && load->getIndx() == store->getIndx()) {
								Blocks::Lock *lock = new Blocks::Lock(m_Method, triumph, dup1->getValue());
								dup2->toTrash();

								m_Statements.erase(m_Statements.begin() + i); delete st1;
								m_Statements.erase(m_Statements.begin() + i); delete st2;

								m_Statements[i] = lock;
								delete st3;
							}
						}
					}
				}
			}
		}
	}*/
}